Spring Boot的Kafka入门

这是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