![](/img/trans.png)
[英]Kafka & Spring Batch - How to read ONLY uncommitted messages from the same topic?
[英]How to ignore uncommitted messages from a Kafka topic
我想要一个能够满足两个要求的 Kakfa 消费者:
为简单起见,我将只运行一个主题和一个分区。 这是我设置消费者的方式:
private Consumer<Long, String> createConsumer() {
final Properties props = new Properties();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(ConsumerConfig.GROUP_ID_CONFIG, "KafkaExampleConsumer");
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName());
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
final Consumer<Long, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Collections.singletonList(topic));
return consumer;
}
这是我用来满足需求编号 1 的方法:
public void write() {
final ConsumerRecords<Long, String> consumerRecords = transactionsConsumer.poll(1000);
consumerRecords.forEach(record -> System.out.printf("Consumer Record:(%d, %s, %d, %d)\n",
record.key(), record.value(), record.partition(), record.offset()));
transactionsConsumer.commitAsync();
}
它工作正常,但是,对于第 2 号要求,我真的不知道什么是最好的处理方式。 我知道我可以只实现一个类似write()
方法,该方法消耗并且不打印任何内容,但这对于忽略消息来说似乎太多了。 另外,如果我有很多消息要消费,我认为这样做可能会很昂贵。 我查看了诸如seekToEnd(partition)
,但无法使其正常工作。
对于读提交的消息,您必须设置
isolation.level=read_committed
在您的消费者配置中。
在 read_committed 模式下,消费者将只读取那些已成功提交的事务消息。 它将像以前一样继续读取非事务性消息。 在 read_committed 模式下没有客户端缓冲。 相反,read_committed 消费者的分区的结束偏移量将是属于打开事务的分区中第一条消息的偏移量。 此偏移量称为“最后稳定偏移量”(LSO)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.