在Spring Boot应用中,可以使用Kafka的消费者监听器来监控消息。以下是一个简单的示例,展示了如何在Spring Boot应用中监控Kafka消息:
pom.xml
文件中添加以下依赖:<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
application.properties
或application.yml
文件中配置Kafka消费者属性。例如: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
public interface KafkaMessageListener {
void onMessage(ConsumerRecord<String, String> record);
}
@Service
public class MyKafkaMessageListener implements KafkaMessageListener {
@Override
public void onMessage(ConsumerRecord<String, String> record) {
// 在这里添加监控逻辑,例如记录日志、发送通知等
System.out.printf("接收到消息: key = %s, value = %s, partition = %d, offset = %d%n",
record.key(), record.value(), record.partition(), record.offset());
}
}
@Configuration
public class KafkaConsumerConfig {
@Autowired
private MyKafkaMessageListener myKafkaMessageListener;
@Bean
public Map<String, Object> consumerConfigs() {
Map<String, Object> props = new HashMap<>();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(ConsumerConfig.GROUP_ID_CONFIG, "my-consumer-group");
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, "earliest");
return props;
}
@Bean
public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerConfigs(consumerConfigs());
factory.setConcurrency(3); // 设置并发消费者数量
factory.getContainerProperties().setAckMode(AckMode.MANUAL); // 设置手动提交偏移量
return factory;
}
@Bean
public ConsumerFactory<String, String> consumerFactory() {
return new DefaultKafkaConsumerFactory<>(consumerConfigs());
}
@Bean
public KafkaListenerEndpointRegistrar endpointRegistrar(KafkaListenerEndpointRegistry registry) {
KafkaListenerEndpointRegistrar registrar = new KafkaListenerEndpointRegistrar(registry);
registrar.setBeanFactory(applicationContext);
return registrar;
}
}
@KafkaListener
注解来定义一个监听器方法:@Service
public class MyKafkaConsumer {
@Autowired
private MyKafkaMessageListener myKafkaMessageListener;
@KafkaListener(topics = "my-topic", groupId = "my-consumer-group")
public void listen(ConsumerRecord<String, String> record) {
myKafkaMessageListener.onMessage(record);
}
}
现在,当有新消息进入my-topic
主题时,MyKafkaConsumer
类中的listen
方法将被调用,MyKafkaMessageListener
接口的onMessage
方法将处理接收到的消息,并执行监控逻辑。