上一篇文章已經將Kafka的服務配置分享了一遍,這篇主要是將java的API分享一波。
Kafka有四個核心API:
- Producer API :允許應用程序發送數據流到kafka集羣中的topic。
- Consumer API :允許應用程序從kafka集羣的topic中讀取數據流。
- Streams API :允許從輸入topic轉換數據流到輸出topic。
- Connect API:通過實現連接器(connector),不斷地從一些源系統或應用程序中拉取數據到kafka,或從kafka提交數據到宿系統(sink system)或應用程序。
但這些Springboot都已經爲我們集成的差不多了,我們只需要發揮拿來主義就可以:
生產者發送消息:
ListenableFuture<SendResult<K, V>> sendDefault(V data);
ListenableFuture<SendResult<K, V>> sendDefault(K key, V data);
ListenableFuture<SendResult<K, V>> sendDefault(Integer partition, K key, V data);
ListenableFuture<SendResult<K, V>> sendDefault(Integer partition, Long timestamp, K key, V data);
ListenableFuture<SendResult<K, V>> send(String topic, V data);
ListenableFuture<SendResult<K, V>> send(String topic, K key, V data);
ListenableFuture<SendResult<K, V>> send(String topic, Integer partition, K key, V data);
ListenableFuture<SendResult<K, V>> send(String topic, Integer partition, Long timestamp, K key, V data);
ListenableFuture<SendResult<K, V>> send(ProducerRecord<K, V> record);
ListenableFuture<SendResult<K, V>> send(Message<?> message);
topic:這裏填寫的是Topic的名字
partition:這裏填寫的是分區的id,其實也是就第幾個分區,id從0開始。表示指定發送到該分區中
timestamp:時間戳,一般默認當前時間戳
key:消息的鍵
data:消息的數據
ProducerRecord:消息對應的封裝類,包含上述字段
Message<?>:Spring自帶的Message封裝類,包含消息及消息頭
監聽更是可以直接將註解@KafkaListener注在方法上就可以:
@KafkaListener的註解都提供了什麼屬性:
- id:消費者的id,當GroupId沒有被配置的時候,默認id爲GroupId
- containerFactory:上面提到了@KafkaListener區分單數據還是多數據消費只需要配置一下註解的containerFactory屬性就可以了,這裏面配置的是監聽容器工廠,也就是ConcurrentKafkaListenerContainerFactory,配置BeanName
- topics:需要監聽的Topic,可監聽多個
- topicPartitions:可配置更加詳細的監聽信息,必須監聽某個Topic中的指定分區,或者從offset爲200的偏移量開始監聽
- errorHandler:監聽異常處理器,配置BeanName
- groupId:消費組ID
- idIsGroup:id是否爲GroupId
- clientIdPrefix:消費者Id前綴
- beanRef:真實監聽容器的BeanName,需要在 BeanName前加 “__”
下一篇我將自己使用Springboot集成Kafka的代碼分享一下,希望大家可以指點一波。