推荐链接:
总结——》【Java】
总结——》【Mysql】
总结——》【Redis】
总结——》【Spring】
总结——》【SpringBoot】
总结——》【MyBatis、MyBatis-Plus】
方法 | 功能 |
---|---|
String id() default “”; | 监听器id |
String containerFactory() default “”; | 监听器工厂 |
String[] topics() default {}; | 监听器topics |
String topicPattern() default “”; | 监听器topics匹配正则表达式 |
TopicPartition[] topicPartitions() default {}; | 监听器分区 |
String errorHandler() default “”; | 异常处理器 |
String groupId() default “”; | 分组id |
boolean idIsGroup() default true; | 是否使用id作为groupId |
@KafkaListener(id = "listenerForSyncEsfCommunity", topics = "test_topic1")
如果ID重复,会报错Caused by: java.lang.IllegalStateException: Another endpoint is already registered with id
kafka.consumer.group-id = xxxxx
// 消费组为xxxxx
@KafkaListener(id = "listenerForSyncEsfCommunity",idIsGroup = false)
// 方式一:消费组为listenerForSyncEsfCommunity
@KafkaListener(id = "listenerForSyncEsfCommunity")
// 方式二:消费组为groupId-test
@KafkaListener(id = "listenerForSyncEsfCommunity",idIsGroup = false,groupId = "groupId-test")
@Bean("kafkaListenerContainerFactory")
KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
// consumerGroupId为空时,会用默认的groupId
factory.setConsumerFactory(consumerFactory("g1"));
factory.setConcurrency(4);
// 设置为批量消费,每个批次数量在Kafka配置参数中设置ConsumerConfig.MAX_POLL_RECORDS_CONFIG
factory.setBatchListener(true);
factory.getContainerProperties().setPollTimeout(3000);
return factory;
}
@KafkaListener(id = "listenerForSyncEsfCommunity", topics = "test_topic1", containerFactory = "kafkaListenerContainerFactory")
// 指定多个topic
@KafkaListener(id = "listenerForSyncEsfCommunity", topics = {"test_topic1","test_topic2"})
自定义配置:kafka.consumer.topics=topic1,topic2
// Spring的SpEl表达式
@KafkaListener(topics = "#{'${kafka.consumer.topics}'.split(',')}")
@KafkaListener(id = "listenerForSyncEsfCommunity", topicPattern = "test_.*topic.*")
@KafkaListener(id = "listenerForSyncEsfCommunity", topicPartitions =
{ @TopicPartition(topic = "topic1", partitions = { "0", "1" }),
@TopicPartition(topic = "topic2", partitions = "0")
})
异常处理有2种方式:
@Component("kafkaErrorHandler")
public class KafkaDefaultListenerErrorHandler implements KafkaListenerErrorHandler {
@Override
public Object handleError(Message<?> message, ListenerExecutionFailedException exception) {
return null;
}
@Override
public Object handleError(Message<?> message, ListenerExecutionFailedException exception, Consumer<?, ?> consumer) {
//TODO
return null;
}
}
// 调用的时候errorHandler的值填写beanName
@KafkaListener(id = "listenerForSyncEsfCommunity", topics = "topic1",errorHandler = "kafkaErrorHandler")
参考监听器id
参考监听器id