SpringBoot整合Kafka(生產者和消費者都是SpringBoot服務)

TD_FAlmK發表於2020-12-02
1、首先在 pom.xml 引入依賴
<dependency>
    <groupId>org.springframework.kafka</groupId>
    <artifactId>spring-kafka</artifactId>
</dependency>

 

2、配置檔案application.properties中配置生產者
###kafka
## producer
spring.kafka.producer.bootstrap-servers=192.168.56.102:9092  #根據自己的地址去配置
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer

 

 
3、配置檔案 application.properties中配置消費者
## consumer
spring.kafka.consumer.bootstrap-servers=192.168.56.102:9092  #根據自己的地址去配置
spring.kafka.consumer.group-id=seconds-kill  #根據自己的group-id去配置
spring.kafka.consumer.auto-offset-reset=earliest
spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.topic=test  #根據自己的主題去配置
spring.kafka.consumer.thread=3

 

 
4、開啟kafka服務(Linux版)(windows版見: https://www.cnblogs.com/flower1990/p/7466882.html
 
Linux版:
啟動 Zookeeper 伺服器:
cd /usr/local/kafka
bin/zookeeper-server-start.sh config/zookeeper.properties

啟動 kafka 服務:
cd /usr/local/kafka
bin/kafka-server-start.sh config/server.properties &

 

windows版:
啟動 Zookeeper 伺服器:
zkServer

啟動 kafka 服務:
首先cd到kafka的安裝目錄
.\bin\windows\kafka-server-start.bat .\config\server.properties

 

5、生產者傳送訊息
//首先引入KafkaTemplate
@Autowired
public KafkaTemplate<String, String> kafkaTempalte;

// 傳送訊息(topic對應上面消費者配置的主題,XXX是內容)
kafkaTempalte.send("topic","XXX");

 

6、消費者接收訊息
@KafkaListener(id="seconds-kill", topics = "test", groupId = "seconds-kill")
    public void listener(ConsumerRecord<?, ?> record) {
        String[] messages = record.value().toString();
        System.out.println(messages);
}

 

相關文章