使用 KafkaTemplate
接收
本節介紹如何使用 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
時,僅支援正的、絕對的偏移量。