一、介绍
注:Kafka 1.1
二、源码分析
三、具体应用
1、需求介绍,
2、代码相关
2.1、pom依赖
producer和consumer均依赖 kafka-clients.
<dependency> <groupId>org.apache.kafka</groupId> <artifactId>kafka-clients</artifactId> <version>1.1.0</version> </dependency>
2.2、Producer
2.2.1、producer configs
Properties properties = new Properties(); properties.put("bootstrap.servers", "ipAndPort"); //指定kafka服务地址,集群的情况用逗号分隔,如:host1:port1,host2:port2 ... properties.put("acks", "all");//表示完成Requests前需要承认的数量。 0:无需承认直接发送到socket 1:需要leader承认 all/-1:需要全部承认后发送 properties.put("retries", 0);//发生错误时,重传次数。当开启重传时,需要将`max.in.flight.requests.per.connection`设置为1,否则可能导致失序 properties.put("batch.size", 16384); properties.put("linger.ms", 1); //1毫秒,简单讲,就是延时1ms,把期间收集到的所有Requests聚合到一起发送,以此提高吞吐量 properties.put("buffer.memory", 33554432);//默认值就是 33554443,缓存数据的内存大小;若生产速度大于Producer向Broker发送速度,会阻塞超时抛出异常 properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); //指定扔到kafka的键值对中键的类型,实例包下还有Long、Double、Short等等 properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); //指定键值对的值类型,具体同上
2.3、Consumer
2.3.1、consumer configs
Properties props = new Properties(); props.put("bootstrap.servers", "IpAndPort"); props.put("enable.auto.commit", "true"); props.put("auto.commit.interval.ms", "1000");//自动提交时间间隔,前提是 enable.auto.commit设置为true props.put("session.timeout.ms", "30000"); props.put("key.deserializer","org.apache.kafka.common.serialization.StringDeserializer");//指定接受到数据的键值对类型 props.put("value.deserializer","org.apache.kafka.common.serialization.StringDeserializer"); props.put("group.id", "unique group id");//指定consumer的唯一group