一、準備工作
參考博主的上一篇文章《kafka 在windows 平臺的搭建和簡單實用》搭建好Kafka環境,確保你的Kafka能正常使用。
二、項目結構
爲了更加體現實際開發需求,一般生產者都是在調用某些接口的服務處理完邏輯之後然後往kafka裏面扔數據,然後有一個消費者不停的監控這個Topic,然後處理數據,所以這裏把生產者作爲一個接口,消費者放到kafka這個目錄下,注意@Component註解,不然掃描不到@KafkaListener
三、具體實現代碼
SpringBoot配置文件
application.yml
spring:
kafka:
bootstrap-servers: 192.168.0.94:9092
producer:
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.apache.kafka.common.serialization.StringSerializer
consumer:
group-id: test
#開啓消費者自動提交最大的偏移量
enable-auto-commit: true
#消費者每隔一秒自動提交接收到的最大的偏移量
auto-commit-interval: 1000
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
生產者
package cn.saytime.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 測試kafka生產者
*/
@RestController
@RequestMapping("kafka")
public class TestKafkaProducerController {
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
@RequestMapping("send")
public String send(String msg){
kafkaTemplate.send("test", msg);
return "success";
}
}
消費者
這裏的消費者會監聽這個主題,有消息就會執行,不需要進行while(true)
package cn.saytime.kafka;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
/**
* kafka消費者測試
*/
@Component
public class TestConsumer {
@KafkaListener(topics = "test")
public void listen (ConsumerRecord<?, ?> record) throws Exception {
System.out.printf("topic = %s, offset = %d, value = %s \n", record.topic(), record.offset(), record.value());
}
}
項目啓動類
package cn.saytime;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TestApplication{
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
四、測試
運行項目,執行:http://localhost:8080/kafka/send?msg=hello
控制檯輸出:
topic = test_topic, offset = 19, value = hello
爲了體現消費者不止執行一次就結束,再調用一次接口:
http://localhost:8080/kafka/send?msg=kafka
topic = test_topic, offset = 20, value = kafka
所以可以看到這裏消費者實際上是不停的poll Topic數據的。
---------------------
作者:saytime
來源:CSDN
原文:https://blog.csdn.net/saytime/article/details/79950635
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!