springboot集成kafka
时间: 2023-08-31 17:10:38 浏览: 145
spring boot集成kafka
要在Spring Boot中集成Kafka,你需要进行以下步骤:
1. 在pom.xml文件中添加Kafka依赖:
```xml
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>2.2.7.RELEASE</version>
</dependency>
```
2. 在application.yml文件中配置Kafka连接信息:
```yml
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=my-group
spring.kafka.consumer.auto-offset-reset=earliest
```
3. 创建一个Kafka生产者:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
@Component
public class KafkaProducer {
private final KafkaTemplate<String, String> kafkaTemplate;
@Autowired
public KafkaProducer(KafkaTemplate<String, String> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
public void sendMessage(String topic, String message) {
kafkaTemplate.send(topic, message);
}
}
```
4. 创建一个Kafka消费者:
```java
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
@Component
public class KafkaConsumer {
@KafkaListener(topics = "my-topic", groupId = "my-group")
public void listen(ConsumerRecord<String, String> record) {
System.out.println("Received message: " + record.value());
}
}
```
5. 发送消息:
```java
@Autowired
private KafkaProducer kafkaProducer;
...
kafkaProducer.sendMessage("my-topic", "Hello, Kafka!");
```
6. 运行应用程序并查看控制台输出,你应该能够看到消费者打印出发送的消息。
这就是在Spring Boot中集成Kafka的基本步骤。你可以根据需要进行更多的配置和自定义,例如设置监听器容器工厂和序列化器等。
阅读全文