在 Spring Boot 中整合 Kafka 消费者,你需要遵循以下步骤:
在你的 pom.xml
文件中添加 Spring Boot Kafka 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-kafka</artifactId>
</dependency>
在 application.properties
或 application.yml
文件中配置 Kafka 消费者属性,例如:
# application.properties
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=my-consumer-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
或者
# application.yml
spring:
kafka:
bootstrap-servers: localhost:9092
consumer:
group-id: my-consumer-group
auto-offset-reset: earliest
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
创建一个配置类,用于设置 Kafka 消费者相关的属性。例如:
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class KafkaConsumerConfig {
@Value("${spring.kafka.bootstrap-servers}")
private String bootstrapServers;
@Value("${spring.kafka.consumer.group-id}")
private String groupId;
@Value("${spring.kafka.consumer.auto-offset-reset}")
private String autoOffsetReset;
@Value("${spring.kafka.consumer.key-deserializer}")
private String keyDeserializer;
@Value("${spring.kafka.consumer.value-deserializer}")
private String valueDeserializer;
@Bean
public Map<String, Object> consumerConfigs() {
Map<String, Object> props = new HashMap<>();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
props.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetReset);
return props;
}
}
创建一个 Kafka 消费者接口,用于定义消费者需要处理的消息方法。例如:
public interface KafkaConsumer {
void consume(String message);
}
然后创建一个实现该接口的类,例如:
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
@Component
public class KafkaMessageConsumer implements KafkaConsumer {
@Override
@KafkaListener(topics = "${spring.kafka.consumer.topic}", groupId = "${spring.kafka.consumer.group-id}")
public void consume(String message) {
System.out.println("Received message: " + message);
}
}
@KafkaListener
注解监听消息在 KafkaMessageConsumer
类中,使用 @KafkaListener
注解监听指定的 Kafka 主题。当有新消息到达时,消费者会自动处理这些消息。
现在你已经成功整合了 Spring Boot 和 Kafka 消费者。当你运行 Spring Boot 应用时,它将自动连接到 Kafka 服务器并消费指定主题的消息。