kafka:java集成 kafka(springboot集成、客户端集成)
Spring Boot 集成 Kafka 的示例代码:
- 添加依赖到
pom.xml
:
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
- 在
application.properties
或application.yml
中配置 Kafka 属性:
# 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
- 创建 Kafka 生产者:
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);
}
}
- 创建 Kafka 消费者:
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
@Component
public class KafkaConsumer {
@KafkaListener(topics = "myTopic", groupId = "myGroup")
public void listen(String message) {
System.out.println("Received message in group myGroup: " + message);
}
}
- 使用 Kafka 生产者发送消息:
@Autowired
private KafkaProducer kafkaProducer;
public void sendMessageExample() {
kafkaProducer.sendMessage("myTopic", "Hello, Kafka!");
}
以上代码展示了如何在 Spring Boot 应用中集成 Kafka,包括配置 Kafka 生产者和消费者。通过 KafkaProducer
类发送消息到指定的 topic,KafkaConsumer
类则监听 topic 并处理接收到的消息。
评论已关闭