使用 KafkaTemplate 接收
KafkaTemplate to Receive
本节介绍如何使用 KafkaTemplate 接收消息。
从版本 2.8 开始,模板有四个 receive() 方法:
ConsumerRecord<K, V> receive(String topic, int partition, long offset);
ConsumerRecord<K, V> receive(String topic, int partition, long offset, Duration pollTimeout);
ConsumerRecords<K, V> receive(Collection<TopicPartitionOffset> requested);
ConsumerRecords<K, V> receive(Collection<TopicPartitionOffset> requested, Duration pollTimeout);
如您所见,您需要知道要检索的记录的分区和偏移量;每个操作都会创建(并关闭)一个新的 Consumer。
使用最后两种方法时,每条记录都是单独检索的,结果被组装成一个 ConsumerRecords 对象。在为请求创建 TopicPartitionOffset 时,仅支持正的、绝对的偏移量。