Spring Boot 集成 Kafka
要在Spring Boot中集成Kafka,你需要做以下几步:
- 添加依赖:在
pom.xml
中添加Spring for Apache Kafka的依赖。
<dependencies>
<!-- Spring Kafka -->
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
<!-- 如果你需要使用Spring Boot配置属性支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>你的Spring Boot版本</version>
</dependency>
</dependencies>
- 配置Kafka:在
application.properties
或application.yml
中配置Kafka连接信息。
# application.properties
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
- 创建生产者和消费者:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
@Service
public class KafkaProducer {
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
public void sendMessage(String topic, String message) {
kafkaTemplate.send(topic, message);
}
}
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
@Component
public class KafkaConsumer {
@KafkaListener(topics = "your-topic", groupId = "my-group")
public void listen(ConsumerRecord<?, ?> record) {
System.out.println(record.value());
}
}
- 启动应用程序,生产者和消费者将开始工作。
确保你的Kafka服务器正在运行,并且配置的topic存在。这样你就可以通过KafkaProducer
发送消息,并通过KafkaConsumer
接收消息了。
评论已关闭