Spring Boot集成Kafka跨微服务消费异常:生产者发消息但消费者未触发
问题场景
现有关联Kafka的Spring Boot微服务集群,常规生产、消费事件均正常,但存在异常场景:
当微服务A的消费者处理完事件后,生产新事件到v1-push-notif主题,期望微服务B的消费者消费该事件,但微服务B的对应消费者方法始终未被触发。
已确认:生产逻辑正常,Kafka中v1-push-notif主题确实存在目标事件。
相关代码片段
微服务A的生产者相关代码
@Component @RequiredArgsConstructor @Slf4j public class TaskListener { private final TaskService taskService; private final KafkaConsumer<TaskEvent> taskConsumer; private final KafkaProducer<String, TaskEvent> producer; private final KafkaTopicProps kafkaTopicProps; @KafkaListener(topics = "v1-add-task", groupId = "add-task", containerFactory = "kafkaListenerContainerFactory") public void consumingAddTask( @Payload TaskEvent message, @Header(name = KafkaHeaders.RECEIVED_PARTITION_ID) int partition, @Header(name = KafkaHeaders.OFFSET) int offset) { log.debug("[START-ADD-TASK-CONSUMER] Message : {}, Partition: {}, Offset: {}", message, partition, offset); taskConsumer.listener(message, partition, offset, event -> { var task = taskService.addTask(event.getBody()); // JPA调用正常 if(task != null && task.getId() != null) { event.setTaskId(task.getId()); producer.send(kafkaTopicProps.taskTopic().getPushNotification(), null, event, null); // 目标主题为v1-push-notif } }); log.debug("[END-ADD-TASK-CONSUMER] Message : {}, Partition: {}, Offset: {}", message, partition, offset); } } @Component @Slf4j public class ConsumerImpl<T extends Event> implements KafkaConsumer<T> { @Override public void listener(T event, int partition, int offset, Consumer<T> consume) { log.info("Start receiving message : Type {}, Partition: {}, Offset: {}", event.getActionType(), partition, offset); consume.accept(event); log.info("end receiving message : Type {}, Partition: {}, Offset: {}", event.getActionType(), partition, offset); } } @Component @Slf4j @RequiredArgsConstructor public class ProducerImpl<K, V> implements KafkaProducer<K, V> { private final KafkaTemplate<K, V> kafkaTemplate; @Override public Future<SendResult<K, V>> send(String topic, K key, V data, BiConsumer<K, V> callback) { log.info("Start sending message : Topic {}, Key: {}", topic, key); CompletableFuture<ListenableFuture<SendResult<K, V>>> future = CompletableFuture.supplyAsync(() -> key != null ? kafkaTemplate.send(topic, key, data) : kafkaTemplate.send(topic, data)); future.thenAccept(sendResult -> { log.info("End sending message : Topic {}, Key: {}", topic, key); if (callback != null) { log.info("Executing callback logic after message sending"); callback.accept(key, data); } }); try { return future.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.error("having interruption error while extracting callback : {}", e.getMessage()); throw new TechnicalException(e); } catch (ExecutionException e) { log.error("having execution error while extracting callback : {}", e.getMessage()); throw new TechnicalException(e); } } }
微服务B的消费者代码
@Component("ATNotificationListener") @RequiredArgsConstructor @Slf4j public class NotificationListener { private final KafkaConsumer<TaskEvent> taskConsumer; private final KafkaProducer<String, TaskEvent> producer; private final NotificationService notificationService; private final KafkaTopicProps kafkaTopicProps; private NotificationMapper notificationMapper = Mappers.getMapper(NotificationMapper.class); @KafkaListener(topics = "v1-push-notif", groupId = "update-at-notification-linked-to-task", containerFactory = "kafkaListenerContainerFactory") public void consumingPushNotificationLinkedToTask( @Payload TaskEvent message, @Header(name = KafkaHeaders.RECEIVED_PARTITION_ID) int partition, @Header(name = KafkaHeaders.OFFSET) int offset) { log.debug("[START-NOTIFICATION-PUSH-CONSUMER] Message : {}, Partition: {}, Offset: {}", message, partition, offset); taskConsumer.listener(message, partition, offset, event -> { var globalNotification = notificationMapper.mapToGlobalNotification(notificationMapper.mapTaskToNotification(event.getBody())); var notification = notificationService.pushNotification(globalNotification); // JPA调用 if(notification != null && notification.getId() != null) { event.setNotificationId(notification.getId()); producer.send(kafkaTopicProps.notificationAtTopic().getUpdateTask(), null, event, null); } }); log.debug("[END-NOTIFICATION-PUSH-CONSUMER] Message : {}, Partition: {}, Offset: {}", message, partition, offset); } }
通用Kafka配置类
@Configuration public class KafkaConfig { @Bean ProducerFactory<String, Object> producerFactory(KafkaProperties kafkaProperties) { Map<String, Object> configProps = kafkaProperties.buildProducerProperties(); configProps.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false); configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); return new DefaultKafkaProducerFactory<>(configProps); } @Bean KafkaTemplate<String, Object> kafkaTemplate(ProducerFactory<String, Object> producerFactory) { return new KafkaTemplate<>(producerFactory); } @Bean public ConsumerFactory<String, Event> consumerFactory(KafkaProperties kafkaProperties, ObjectMapper objectMapper) { Map<String, Object> props = kafkaProperties.buildConsumerProperties(); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ErrorHandlingDeserializer.class); props.put(ErrorHandlingDeserializer.VALUE_DESERIALIZER_CLASS, JsonDeserializer.class); var jsonDeserializer = new JsonDeserializer<>(Event.class, objectMapper, true); jsonDeserializer.addTrustedPackages("com.pj.notification.event"); return new DefaultKafkaConsumerFactory<>(props, new StringDeserializer(), jsonDeserializer); } @Bean KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, Event>> kafkaListenerContainerFactory( ConsumerFactory<String, Event> consumerFactory) { var factory = new ConcurrentKafkaListenerContainerFactory<String, Event>(); factory.setConsumerFactory(consumerFactory); factory.setRecordInterceptor(new KafkaConsumerInterceptor<>()); factory.getContainerProperties().setAuthExceptionRetryInterval(Duration.ofSeconds(7)); factory.setCommonErrorHandler(new KafkaErrorHandler()); return factory; } }
排查方向及解决方案
1. 反序列化信任包不匹配
问题分析:
微服务B的JsonDeserializer仅添加了com.pj.notification.event到信任包,但生产的TaskEvent大概率属于其他包(如com.pj.task.event),导致反序列化失败,且被ErrorHandlingDeserializer吞掉异常,消费者方法无法触发。
解决方案:
扩展信任包范围,添加TaskEvent所在的包:
jsonDeserializer.addTrustedPackages("com.pj.notification.event", "com.pj.task.event"); // 测试环境可临时允许所有包(生产不建议) // jsonDeserializer.addTrustedPackages("*");
2. 消费者组偏移量异常
问题分析:
消费者组update-at-notification-linked-to-task可能已提交过该主题的最新偏移量,新消息无法被拉取;或该组未被分配到主题分区。
解决方案:
- 查看消费者组偏移量:
kafka-consumer-groups.sh --bootstrap-server <KAFKA地址> --describe --group update-at-notification-linked-to-task
- 重置偏移量到最早位置:
kafka-consumer-groups.sh --bootstrap-server <KAFKA地址> --reset-offsets --to-earliest --topic v1-push-notif --group update-at-notification-linked-to-task --execute
3. 生产者异步逻辑冗余
问题分析:
ProducerImpl中用CompletableFuture.supplyAsync嵌套包装kafkaTemplate.send()(本身已返回异步ListenableFuture),再调用future.get()阻塞等待,虽不影响消息发送,但可能引发不必要的线程阻塞问题。
优化方案:
简化生产者代码,直接使用kafkaTemplate的异步回调:
@Override public Future<SendResult<K, V>> send(String topic, K key, V data, BiConsumer<K, V> callback) { log.info("Start sending message : Topic {}, Key: {}", topic, key); ListenableFuture<SendResult<K, V>> listenableFuture = key != null ? kafkaTemplate.send(topic, key, data) : kafkaTemplate.send(topic, data); listenableFuture.addCallback( success -> { log.info("End sending message : Topic {}, Key: {}", topic, key); if (callback != null) { log.info("Executing callback logic after message sending"); callback.accept(key, data); } }, failure -> { log.error("Failed to send message : Topic {}, Key: {}, Error: {}", topic, key, failure.getMessage()); throw new TechnicalException(failure); } ); return listenableFuture; }
4. 拦截器/错误处理器拦截消息
问题分析:
kafkaListenerContainerFactory配置的KafkaConsumerInterceptor或KafkaErrorHandler可能存在逻辑问题,导致消息被拦截或忽略。
解决方案:
临时注释拦截器和错误处理器配置,测试消费者是否正常触发:
// factory.setRecordInterceptor(new KafkaConsumerInterceptor<>()); // factory.setCommonErrorHandler(new KafkaErrorHandler());
若恢复正常,再排查拦截器和错误处理器的具体逻辑。
5. 主题名称一致性校验
问题分析:
Kafka主题名称大小写敏感,需确认生产者发送的主题名称与消费者监听的名称完全一致。
解决方案:
在微服务A的生产者发送时添加日志,打印实际主题名称,与微服务B的监听主题对比:
log.info("Sending message to target topic: {}", kafkaTopicProps.taskTopic().getPushNotification());
内容的提问来源于stack exchange,提问作者Oussama Abouzid

