springboot整合kafaka
时间: 2023-04-14 19:00:42 浏览: 107
springboot整合kafka
Spring Boot可以很方便地与Kafka集成,以下是整合步骤:
1. 添加Kafka依赖
在pom.xml文件中添加Kafka依赖:
```
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>2.5.4.RELEASE</version>
</dependency>
```
2. 配置Kafka
在application.properties文件中添加Kafka配置:
```
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=my-group
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.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer
```
3. 创建Kafka生产者
使用Spring Boot的KafkaTemplate类创建Kafka生产者:
```
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
public void sendMessage(String topic, String message) {
kafkaTemplate.send(topic, message);
}
```
4. 创建Kafka消费者
使用Spring Boot的@KafkaListener注解创建Kafka消费者:
```
@KafkaListener(topics = "my-topic", groupId = "my-group")
public void listen(String message) {
System.out.println("Received message: " + message);
}
```
以上就是Spring Boot整合Kafka的基本步骤,可以根据实际需求进行调整和扩展。
阅读全文