springboot集成kafka代码
时间: 2023-09-17 20:07:48 浏览: 113
springboot-kafka_springboot_kafka_
很高兴能回答这个问题!在Spring Boot中集成Kafka,需要进行如下步骤:
1. 添加Kafka依赖
在pom.xml文件中添加Kafka依赖:
```xml
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>${spring-kafka.version}</version>
</dependency>
```
2. 配置Kafka
在application.yml或application.properties文件中配置Kafka相关信息,示例如下:
```yaml
spring:
kafka:
bootstrap-servers: localhost:9092
producer:
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.apache.kafka.common.serialization.StringSerializer
consumer:
group-id: group-id-1
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
```
3. 实现Kafka生产者
在需要发送消息的地方,注入KafkaTemplate,然后调用send方法:
```java
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
public void sendMessage(String topic, String message) {
kafkaTemplate.send(topic, message);
}
```
4. 实现Kafka消费者
使用@KafkaListener注解实现Kafka消费者:
```java
@KafkaListener(groupId = "group-id-1", topics = "test")
public void receiveMessage(String message) {
// 处理消息
}
```
以上就是Spring Boot集成Kafka的基本步骤,希望对你有所帮助!
阅读全文