1. 程式人生 > >kafka在Java整合小例子

kafka在Java整合小例子


kafka
是吞吐量巨大的一個訊息系統,它是用scala寫的,和普通的訊息的生產消費還有所不同,寫了個demo程式供大家參考。kafka的安裝請參考官方文件。

首先我們需要新建一個maven專案,然後在pom中引用kafka jar包,引用依賴如下:

  1. <dependency>
  2.     <groupId>org.apache.kafka</groupId>
  3.     <artifactId>kafka_2.10</artifactId>
  4.     <version>0.8.0</version>
  5. </dependency>

我們用的版本是0.8, 下面我們看下生產訊息的程式碼:

  1. package cn.outofmemory.kafka;  
  2. import java.util.Properties;  
  3. import kafka.javaapi.producer.Producer;  
  4. import kafka.producer.KeyedMessage;  
  5. import kafka.producer.ProducerConfig;  
  6. /** 
  7.  * Hello world! 
  8.  * 
  9.  */
  10. publicclass KafkaProducer   
  11. {  
  12.     privatefinal Producer<String, String> producer;  
  13.     public
    finalstatic String TOPIC = "TEST-TOPIC";  
  14.     private KafkaProducer(){  
  15.         Properties props = new Properties();  
  16.         //此處配置的是kafka的埠
  17.         props.put("metadata.broker.list""192.168.193.148:9092");  
  18.         //配置value的序列化類
  19.         props.put("serializer.class""kafka.serializer.StringEncoder");  
  20.         //配置key的序列化類
  21.         props.put("key.serializer.class""kafka.serializer.StringEncoder");  
  22.         //request.required.acks
  23.         //0, which means that the producer never waits for an acknowledgement from the broker (the same behavior as 0.7). This option provides the lowest latency but the weakest durability guarantees (some data will be lost when a server fails).
  24.         //1, which means that the producer gets an acknowledgement after the leader replica has received the data. This option provides better durability as the client waits until the server acknowledges the request as successful (only messages that were written to the now-dead leader but not yet replicated will be lost).
  25.         //-1, which means that the producer gets an acknowledgement after all in-sync replicas have received the data. This option provides the best durability, we guarantee that no messages will be lost as long as at least one in sync replica remains.
  26.         props.put("request.required.acks","-1");  
  27.         producer = new Producer<String, String>(new ProducerConfig(props));  
  28.     }  
  29.     void produce() {  
  30.         int messageNo = 1000;  
  31.         finalint COUNT = 10000;  
  32.         while (messageNo < COUNT) {  
  33.             String key = String.valueOf(messageNo);  
  34.             String data = "hello kafka message " + key;  
  35.             producer.send(new KeyedMessage<String, String>(TOPIC, key ,data));  
  36.             System.out.println(data);  
  37.             messageNo ++;  
  38.         }  
  39.     }  
  40.     publicstaticvoid main( String[] args )  
  41.     {  
  42.         new KafkaProducer().produce();  
  43.     }  
  44. }  

下面是消費端的程式碼實現:

  1. package cn.outofmemory.kafka;  
  2. import java.util.HashMap;  
  3. import java.util.List;  
  4. import java.util.Map;  
  5. import java.util.Properties;  
  6. import kafka.consumer.ConsumerConfig;  
  7. import kafka.consumer.ConsumerIterator;  
  8. import kafka.consumer.KafkaStream;  
  9. import kafka.javaapi.consumer.ConsumerConnector;  
  10. import kafka.serializer.StringDecoder;  
  11. import kafka.utils.VerifiableProperties;  
  12. publicclass KafkaConsumer {  
  13.     privatefinal ConsumerConnector consumer;  
  14.     private KafkaConsumer() {  
  15.         Properties props = new Properties();  
  16.         //zookeeper 配置
  17.         props.put("zookeeper.connect""192.168.193.148:2181");  
  18.         //group 代表一個消費組
  19.         props.put("group.id""jd-group");  
  20.         //zk連線超時
  21.         props.put("zookeeper.session.timeout.ms""4000");  
  22.         props.put("zookeeper.sync.time.ms""200");  
  23.         props.put("auto.commit.interval.ms""1000");  
  24.         props.put("auto.offset.reset""smallest");  
  25.         //序列化類
  26.         props.put("serializer.class""kafka.serializer.StringEncoder");  
  27.         ConsumerConfig config = new ConsumerConfig(props);  
  28.         consumer = kafka.consumer.Consumer.createJavaConsumerConnector(config);  
  29.     }  
  30.     void consume() {  
  31.         Map<String, Integer> topicCountMap = new HashMap<String, Integer>();  
  32.         topicCountMap.put(KafkaProducer.TOPIC, new Integer(1));  
  33.         StringDecoder keyDecoder = new StringDecoder(new VerifiableProperties());  
  34.         StringDecoder valueDecoder = new StringDecoder(new VerifiableProperties());  
  35.         Map<String, List<KafkaStream<String, String>>> consumerMap =   
  36.                 consumer.createMessageStreams(topicCountMap,keyDecoder,valueDecoder);  
  37.         KafkaStream<String, String> stream = consumerMap.get(KafkaProducer.TOPIC).get(0);  
  38.         ConsumerIterator<String, String> it = stream.iterator();  
  39.         while (it.hasNext())  
  40.             System.out.println(it.next().message());  
  41.     }  
  42.     publicstaticvoid main(String[] args) {  
  43.         new KafkaConsumer().consume();  
  44.     }  
  45. }  

注意消費端需要配置成zk的地址,而生產端配置的是kafka的ip和埠。