Spring Boot 配置Kafka

时间:2024-12-21 15:34:23

在Spring Boot中配置Kafka,你需要在application.properties或application.yml文件中设置Kafka的基本属性,并且添加必要的依赖。

以下是一个配置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

spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer

spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer

或者使用application.yml配置文件:

spring:

  kafka:

    bootstrap-servers: localhost:9092

    consumer:

      group-id: my-group

      auto-offset-reset: earliest

      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer

      value-deserializer: org.apache.kafka.common.serialization.StringDeserializer

    producer:

      key-serializer: org.apache.kafka.common.serialization.StringSerializer

      value-serializer: org.apache.kafka.common.serialization.StringSerializer

确保你的pom.xml包含了Spring Kafka依赖:

<dependency>

    <groupId>org.springframework.kafka</groupId>

    <artifactId>spring-kafka</artifactId>

    <version>2.8.0</version> <!-- Use the appropriate version -->

</dependency>

接下来,你可以创建生产者和消费者来发送和接收消息:

生产者:

@Autowired

private KafkaTemplate<String, String> kafkaTemplate;

public void sendMessage(String topic, String message) {

    kafkaTemplate.send(topic, message);

}

消费者:

@Component

@KafkaListener(topics = "your-topic", groupId = "my-group")

public class KafkaConsumer {

    @Autowired

    private ObjectMapper objectMapper;

    public void listen(ConsumerRecord<?, ?> record) {

        String message = (String) record.value();

        System.out.println("Received message in group 'my-group': " + message);

    }

}

确保你的Kafka服务器正在运行,并且你的Spring Boot应用程序可以连接到它。这样你就可以通过生产者发送消息到指定的topic,并通过消费者接收这些消息了。