Java实现Kafka读写笔记

来源:互联网 发布:五官立体知乎 编辑:程序博客网 时间:2024/06/05 05:36
[html] view plain copy
  1. 1.POM.XML  
[html] view plain copy
  1. <dependencies>  
  2.         <dependency>  
  3.             <groupId>org.apache.kafka</groupId>  
  4.             <artifactId>kafka-clients</artifactId>  
  5.             <version>0.8.2.1</version>  
  6.         </dependency>  
  7.   
  8.         <dependency>  
  9.             <groupId>org.apache.kafka</groupId>  
  10.             <artifactId>kafka_2.11</artifactId>  
  11.             <version>0.8.2.1</version>  
  12.         </dependency>  
  13.     </dependencies>  



2.生成者

[java] view plain copy
  1. import kafka.javaapi.producer.Producer;  
  2. import kafka.producer.KeyedMessage;  
  3. import kafka.producer.ProducerConfig;  
  4.   
  5. import java.util.Properties;  
  6.   
  7. public class RunKafkaProduce {  
  8.   
  9.     private final Producer<String, String> producer;  
  10.     public final static String TOPIC = "logstest";  
  11.   
  12.     private RunKafkaProduce(){  
  13.   
  14.         Properties props = new Properties();  
  15.   
  16.         // 此处配置的是kafka的broker地址:端口列表  
  17.         props.put("metadata.broker.list""172.19.4.230:9092");  
  18.   
  19.         //配置value的序列化类  
  20.         props.put("serializer.class""kafka.serializer.StringEncoder");  
  21.   
  22.         //配置key的序列化类  
  23.         props.put("key.serializer.class""kafka.serializer.StringEncoder");  
  24.   
  25.         //request.required.acks  
  26.         //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).  
  27.         //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).  
  28.         //-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.  
  29.         props.put("request.required.acks","-1");  
  30.   
  31.         producer = new Producer<String, String>(new ProducerConfig(props));  
  32.     }  
  33.   
  34.     void produce() {  
  35.         int messageNo = 1;  
  36.         final int COUNT = 101;  
  37.   
  38.         int messageCount = 0;  
  39.         while (messageNo < COUNT) {  
  40.             String key = String.valueOf(messageNo);  
  41.             String data = "Hello kafka message :" + key;  
  42.             producer.send(new KeyedMessage<String, String>(TOPIC, key ,data));  
  43.             System.out.println(data);  
  44.             messageNo ++;  
  45.             messageCount++;  
  46.         }  
  47.   
  48.         System.out.println("Producer端一共产生了" + messageCount + "条消息!");  
  49.     }  
  50.   
  51.     public static void main( String[] args )  
  52.     {  
  53.         new RunKafkaProduce().produce();  
  54.     }  
  55.   
  56. }  



3.消费着


[java] view plain copy
  1. import kafka.consumer.ConsumerConfig;  
  2. import kafka.consumer.ConsumerIterator;  
  3. import kafka.consumer.KafkaStream;  
  4. import kafka.javaapi.consumer.ConsumerConnector;  
  5. import kafka.serializer.StringDecoder;  
  6. import kafka.utils.VerifiableProperties;  
  7. import org.apache.kafka.clients.producer.KafkaProducer;  
  8.   
  9. import java.util.HashMap;  
  10. import java.util.List;  
  11. import java.util.Map;  
  12. import java.util.Properties;  
  13.   
  14. /** 
  15.  * //////////////////////////////////////////////////////////////////// 
  16.  * //                          _ooOoo_                               // 
  17.  * //                         o8888888o                              // 
  18.  * //                         88" . "88                              // 
  19.  * //                         (| ^_^ |)                              // 
  20.  * //                         O\  =  /O                              // 
  21.  * //                      ____/`---'\____                           // 
  22.  * //                    .'  \\|     |//  `.                         // 
  23.  * //                   /  \\|||  :  |||//  \                        // 
  24.  * //                  /  _||||| -:- |||||-  \                       // 
  25.  * //                  |   | \\\  -  /// |   |                       // 
  26.  * //                  | \_|  ''\---/''  |   |                       // 
  27.  * //                  \  .-\__  `-`  ___/-. /                       // 
  28.  * //                ___`. .'  /--.--\  `. . ___                     // 
  29.  * //              ."" '<  `.___\_<|>_/___.'  >'"".                  // 
  30.  * //            | | :  `- \`.;`\ _ /`;.`/ - ` : | |                 // 
  31.  * //            \  \ `-.   \_ __\ /__ _/   .-` /  /                 // 
  32.  * //      ========`-.____`-.___\_____/___.-`____.-'========         // 
  33.  * //                           `=---='                              // 
  34.  * //      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        // 
  35.  * //         佛祖保佑              再无Bug                             // 
  36.  * //////////////////////////////////////////////////////////////////// 
  37.  * User:Klin 
  38.  * Date:2017/4/18 0018 
  39.  */  
  40. public class RunKafkaConsumer {  
  41.   
  42.     private final ConsumerConnector consumer;  
  43.   
  44.     private final static  String TOPIC="logstest";  
  45.   
  46.     private RunKafkaConsumer(){  
  47.         Properties props=new Properties();  
  48.         //zookeeper  
  49.         props.put("zookeeper.connect","zero230:2181");  
  50.         //topic  
  51.         props.put("group.id","logstest");  
  52.   
  53.         //Zookeeper 超时  
  54.         props.put("zookeeper.session.timeout.ms""4000");  
  55.         props.put("zookeeper.sync.time.ms""200");  
  56.         props.put("auto.commit.interval.ms""1000");  
  57.         props.put("auto.offset.reset""smallest");  
  58.   
  59.   
  60.         props.put("serializer.class""kafka.serializer.StringEncoder");  
  61.   
  62.         ConsumerConfig config=new ConsumerConfig(props);  
  63.   
  64.         consumer= kafka.consumer.Consumer.createJavaConsumerConnector(config);  
  65.     }  
  66.   
  67.   
  68.     void consume(){  
  69.         Map<String, Integer> topicCountMap = new HashMap<String, Integer>();  
  70.         topicCountMap.put(TOPIC, new Integer(1));  
  71.   
  72.         StringDecoder keyDecoder = new StringDecoder(new VerifiableProperties());  
  73.         StringDecoder valueDecoder = new StringDecoder(new VerifiableProperties());  
  74.   
  75.         Map<String, List<KafkaStream<String, String>>> consumerMap =  
  76.                 consumer.createMessageStreams(topicCountMap,keyDecoder,valueDecoder);  
  77.         KafkaStream<String, String> stream = consumerMap.get(TOPIC).get(0);  
  78.         ConsumerIterator<String, String> it = stream.iterator();  
  79.   
  80.         int messageCount = 0;  
  81.         while (it.hasNext()){  
  82.             System.out.println(it.next().message());  
  83.             messageCount++;  
  84.             if(messageCount == 100){  
  85.                 System.out.println("Consumer端一共消费了" + messageCount + "条消息!");  
  86.             }  
  87.         }  
  88.     }  
  89.   
  90.     public static void main(String[] args) {  
  91.         new RunKafkaConsumer().consume();  
  92.     }  
  93.   
  94. }