4.4 Kafka Consumer API之手动控制一个或多个分区的消费
原创
©著作权归作者所有:来自51CTO博客作者wx63560c7d74933的原创作品,请联系作者获取转载授权,否则将追究法律责任
1.代码示例
public class ConsumerSample {
private static final String topicName = "steven";
public static void main(String[] args) {
//Consumer配置
Properties props = new Properties();
props.setProperty("bootstrap.servers", "127.0.0.1:9092");
props.setProperty("group.id", "test");
props.setProperty("enable.auto.commit", "false");
//enable.auto.commit设置为false后,下面这一项便不会生效
props.setProperty("auto.commit.interval.ms", "1000");
props.setProperty("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.setProperty("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
//Consumer的主对象
KafkaConsumer<String, String> consumer = new KafkaConsumer(props);
//订阅某个topic的某个partition
TopicPartition p0 = new TopicPartition(topicName, 0);
TopicPartition p1 = new TopicPartition(topicName, 1);
consumer.assign(Arrays.asList(p0));
while (true) {
//批量拉取消息
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(10000));
//每个partition单独处理
for (TopicPartition partition : records.partitions()) {
List<ConsumerRecord<String, String>> pRecord = records.records(partition);
for (ConsumerRecord<String, String> record : pRecord) {
System.out.printf("partition = %d,offset = %d,key = %s,value = %s%n", record.partition(), record.offset(), record.key(), record.value());
}
long lastOffset = pRecord.get(pRecord.size() - 1).offset();
//单个partition中的offset,并且进行提交
Map<TopicPartition, OffsetAndMetadata> offset = new HashMap<>();
offset.put(partition, new OffsetAndMetadata(lastOffset + 1));
// 提交offset
consumer.commitSync(offset);
System.out.println("=============partition - " + partition + " end================");
}
}
}
}
2.代码运行结果
(1).控制台输出
运行自定义分区负载均衡发送示例代码向kafka发送10条数据,然后再执行ConsumerSample代码进行消费,便可在控制台看见代码中指定的输出信息。
partition = 0,offset = 0,key = key-0,value = value-0
partition = 0,offset = 1,key = key-2,value = value-2
partition = 0,offset = 2,key = key-4,value = value-4
partition = 0,offset = 3,key = key-6,value = value-6
partition = 0,offset = 4,key = key-8,value = value-8
=============partition - steven-0 end================
(2).终端输出
打开一个cmd终端,在E:\Kafka\kafka_2.12-1.1.0\bin\windows目录下执行kafka-console-consumer.bat --zookeeper localhost:2181 --topic steven,可以看到生产的消息。