kafka是一个高性能的消息中间件,支持实时,批量,和流处理方式,现已被很多公司应用于web级别的应用上。本篇文章展示了怎么利用kafka的api来创建客户端程序,并且展示了三种语义的客户端的创建方法:至多一次(at-most-once),至少一次( at-least-once),精确一次(and exactly-once )。
首先,在你本机上安装kafka,快速开始点这里,这里假设你们已经安装了kafka并且在运行,Zookeeper 默认端口2181, kafka默认端口 9092. 当kafka运行起来之后,创建一个名为”normal-topic”,分区数为2的topic,命令如下:
bin/kafka-topics –zookeeper localhost:2181 –create –topic normal-topic –partitions 2 –replication-factor 1
查看创建的topic状态:
bin/kafka-topics –list –topic normal-topic –zookeeper localhost:2181
好了,前提步骤做完,接下来是创建kafka客户端。
1.Producer
producer是往topic里发送消息的,consumer则负责接受topic的消息并进行处理,producer代码如下:
public class ProducerExample {
public static void main(String[] str) throws InterruptedException, IOException {
System.out.println("Starting ProducerExample ...");
sendMessages();
}
private static void sendMessages() throws InterruptedException, IOException {
Producer<String, String> producer = createProducer();
sendMessages(producer);
// Allow the producer to complete sending of the messages before program exit.
Thread.sleep(20);
}
private static Producer<String, String> createProducer() {
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("acks", "all");
props.put("retries", 0);
// 批量发送个数
props.put("batch.size", 10);
props.put("linger.ms", 1);
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
return new KafkaProducer(props);
}
private static void sendMessages(Producer<String, String> producer) {
String topic = "normal-topic";
int partition = 0;
long record = 1;
for (int i = 1; i <= 10; i++) {
producer.send(
new ProducerRecord<String, String>(topic, partition, Long.toString(record),Long.toString(record++)));
}
}
}
2.Consumer
consumer注册到kafka的几种方法:
>1. subscribe, 当有consumer通过subcscribe注册的时候,kafka会进行负载均衡,(topic的增加或删除也会导致负载均衡)这个方法有两个:
(a) 2参数,一个topic, 一个listener. 以这种方式注册,当负载均衡的时候,kafka会通知这个consumer. 这个listener可以使手动管理offset(要做到精确一次必须手动管理offset,至少现在版本是)
(b)只有一个topic参数,
>2. assign方法。使用这个方法,kafka不会进行负载均衡。
下面的至少一次,至多一次,都是用的1(b)中的方法,精确一次有两种方式,1(a)和 2。
至多一次 (0或1次)
kafka consumer是默认至多一次,consumer的配置是:
>1. 设置‘enable.auto.commit’ 为 true.
>2. 设置 ‘auto.commit.interval.ms’ 为一个较小的值.
>3. consumer不去执行 consumer.commitSync(), 这样, Kafka 会每隔一段时间自动提交offset。