Using KafkaTemplate
to Receive
本部分介绍如何使用 KafkaTemplate
来接收消息。
This section covers how to use KafkaTemplate
to receive messages.
从 2.8 版开始,该模板有四个 receive()
方法:
Starting with version 2.8, the template has four receive()
methods:
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
。
As you can see, you need to know the partition and offset of the record(s) you need to retrieve; a new Consumer
is created (and closed) for each operation.
使用最后两个方法,会分别检索每条记录,并将结果组合到 ConsumerRecords
对象中。在为请求创建 TopicPartitionOffset
时,仅支持正绝对偏移量。
With the last two methods, each record is retrieved individually and the results assembled into a ConsumerRecords
object.
When creating the `TopicPartitionOffset`s for the request, only positive, absolute offsets are supported.