1. 程式人生 > >kafka初探 版本0.10 java程式設計

kafka初探 版本0.10 java程式設計

之前對kafka的瞭解其實僅限於知道它是一個分散式訊息系統,這次詳細瞭解了下,知道了一些關鍵概念(topic主題、broker服務、producers訊息釋出者、consumer訊息訂閱者消費者),具體網上一大堆,這裡不贅述,直接開始程式碼。

1.引入包

    <dependency>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka_2.10</artifactId>
        <version>0.10.0.0</version
>
</dependency>

實際上我倒不是以上面方式引入的,因為使用kafka還是為了後面跟spark steaming整合,所以我是引入的spark-streaming-kafka,依賴包自然會被引入,需求相同的話可以像下面這樣引入。

    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-streaming-kafka-0-10_2.11</artifactId>
        <version
>
2.3.1</version> </dependency>

2.釋出者類Producer

這裡使用KafkaProducer類,官方已經不建議使用Producer類,實現一個執行緒類,進行訊息釋出,實際的程式碼其實很簡單,不過本來也就是要一個demo。

import java.util.Properties;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;

public class
UserKafkaProducer extends Thread {
private final KafkaProducer<Integer, String> producer; private final String topic; private final Properties props = new Properties(); public UserKafkaProducer(String topic) { props.put("metadata.broker.list", "master2:6667"); props.put("bootstrap.servers", "master2:6667"); props.put("acks", "all"); props.put("retries", 0); props.put("batch.size", 16384); props.put("linger.ms", 1); props.put("buffer.memory", 33554432); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); producer = new KafkaProducer<Integer, String>(props); this.topic = topic; } @Override public void run() { int messageNo = 1; while (true) { String messageStr = new String("Message_" + messageNo); System.out.println("Send:" + messageStr); producer.send(new ProducerRecord<Integer, String>(topic, messageStr)); messageNo++; try { sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
  • 3.訊息消費者類Consumer
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import kafka.consumer.ConsumerConfig;
import kafka.javaapi.consumer.ConsumerConnector;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;

public class UserKafkaConsumer extends Thread
{
    private final ConsumerConnector consumer;
    private final String topic;
    public UserKafkaConsumer(String topic)
    {
        consumer = kafka.consumer.Consumer.createJavaConsumerConnector(
                createConsumerConfig());
        this.topic = topic;
    }
    private static ConsumerConfig createConsumerConfig()
    {
        Properties props = new Properties();
        props.put("zookeeper.connect", "master1:2181,master2:2181");
        props.put("group.id", "group1");
        props.put("zookeeper.session.timeout.ms", "40000");
        props.put("zookeeper.sync.time.ms", "200");
        props.put("auto.commit.interval.ms", "1000");
        return new ConsumerConfig(props);
    }
    @Override
    public void run() {
        Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
        topicCountMap.put(topic, new Integer(1));
        Map<String, List<KafkaStream<byte[], byte[]>>> consumerMap = consumer.createMessageStreams(topicCountMap);
        KafkaStream<byte[], byte[]> stream = consumerMap.get(topic).get(0);
        ConsumerIterator<byte[], byte[]> it = stream.iterator();
        while (it.hasNext()) {
            System.out.println("receive:" + new String(it.next().message()));
            try {
                sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
  • 4.簡單示例
public static void main(String[] args)
    {
        UserKafkaProducer producerThread = new UserKafkaProducer(KafkaProperties.topic);
        producerThread.start();
        UserKafkaConsumer consumerThread = new UserKafkaConsumer(KafkaProperties.topic);
        consumerThread.start();
    }
  • 執行即可。