Spring Boot的Kafka入門

banq發表於2018-09-12
這是Spring Boot使用Kafka入門,生產使用建議Spring Cloud Stream:這裡

1. 新增依賴項:

<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>


在application.properties檔案中設定幾個屬性:

spring.kafka.consumer.group-id=kafka-intro
spring.kafka.bootstrap-servers=
localhost
:9092



2.傳送訊息:
傳送訊息需要@Autowire KafkaTemplate:

@Autowired
private KafkaTemplate<String, String> kafkaTemplate;

public void send(String topic, String payload) {
kafkaTemplate.send(topic, payload);
System.out.println("Message: "+payload+" sent to topic: "+topic);
}



3.接受訊息
需要建立@KafkaListener並選擇要收聽的主題

@KafkaListener(topics = "topic1")
public void receiveTopic1(ConsumerRecord<?, ?> consumerRecord) {
System.out.println("Receiver on topic1: "+consumerRecord.toString());
}


就這麼簡單。

原始碼:Githu

Getting Started with Kafka in Spring Boot | E4deve

相關文章