使用 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 物件。在為請求建立 TopicPartitionOffsets 時,只支援正的絕對偏移量。

© . This site is unofficial and not affiliated with VMware.