Spring Boot 整合 Kafka 配置教程 - 从入门到实战
Spring Boot 整合 Kafka 配置教程 - 从入门到实战
本文将详细介绍如何在 Spring Boot 中整合 Kafka,包括添加依赖、配置 Kafka 连接、创建生产者和消费者,以及示例代码演示。
1. 添加依赖
首先,需要在 pom.xml 文件中添加 Spring Kafka 的依赖:
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
2. 配置 Kafka 连接
在 application.properties 或 application.yml 文件中配置 Kafka 连接信息,例如:
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=my-group
3. 创建生产者
使用 KafkaTemplate 类来发送消息。可以在需要发送消息的地方注入 KafkaTemplate 并调用其 send 方法。例如:
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
public void sendMessage(String topic, String message) {
kafkaTemplate.send(topic, message);
}
4. 创建消费者
使用 @KafkaListener 注解来创建消费者。在需要消费消息的方法上添加 @KafkaListener 注解,指定要监听的 topic。例如:
@KafkaListener(topics = 'my-topic')
public void receiveMessage(String message) {
// 处理接收到的消息
}
以上是整合 Kafka 的基本配置和使用方法,根据实际需求可以进行更详细的配置和处理。
原文地址: https://www.cveoy.top/t/topic/peVS 著作权归作者所有。请勿转载和采集!