Apache kafka 回复卡夫卡模板-异常处理
我正在使用ReplyingKafkaTemplate在两个微服务之间建立同步调用。 事件的接收者用SendTo注释如下:Apache kafka 回复卡夫卡模板-异常处理,apache-kafka,spring-kafka,Apache Kafka,Spring Kafka,我正在使用ReplyingKafkaTemplate在两个微服务之间建立同步调用。 事件的接收者用SendTo注释如下: @KafkaListener(topics = "${kafka.topic.prefix}" + "${kafka.topic.name}", containerFactory = "customEventKafkaListenerFactory") @SendTo public CustomResponseEvent onMessage(
@KafkaListener(topics = "${kafka.topic.prefix}"
+ "${kafka.topic.name}", containerFactory = "customEventKafkaListenerFactory")
@SendTo
public CustomResponseEvent onMessage(
@Payload @Valid CustomRequestEvent event, @Header(KafkaHeaders.CORRELATION_ID) String correlationId,
@Header(KafkaHeaders.REPLY_TOPIC) String replyTopic) {
//Making some REST API calls to another external system here using RestTemplate
}
RESTAPI调用可以抛出4xx或5xx。有多个这样的调用,一些调用到内部系统,另一些调用到外部系统。这可能是一个糟糕的设计,但我们不要再讨论它了
我希望为RestTemplate提供一个全局异常处理程序,在这里我可以捕获所有异常,然后将响应返回给事件的原始发送者。
我使用在消费者中收到的相同replyTopic和correlationId发布事件。
但是响应的接收者仍然不会抛出挂起的应答异常
无论我采用上述哪种方法,都有可能实现这样一个中央错误响应事件发布器吗?
是否有其他最适合此异常处理的替代方案?
@KafkaListener随附:
/**
* Set an {@link org.springframework.kafka.listener.KafkaListenerErrorHandler} bean
* name to invoke if the listener method throws an exception.
* @return the error handler.
* @since 1.3
*/
String errorHandler() default "";
该异常用于捕获和处理所有下游异常,如果返回结果,则返回replyTopic:
有关更多信息,请参阅RecordMessagingMessageListenerAdapter源代码
public void onMessage(ConsumerRecord<K, V> record, Acknowledgment acknowledgment, Consumer<?, ?> consumer) {
Message<?> message = toMessagingMessage(record, acknowledgment, consumer);
logger.debug(() -> "Processing [" + message + "]");
try {
Object result = invokeHandler(record, acknowledgment, message, consumer);
if (result != null) {
handleResult(result, record, message);
}
}
catch (ListenerExecutionFailedException e) { // NOSONAR ex flow control
if (this.errorHandler != null) {
try {
Object result = this.errorHandler.handleError(message, e, consumer);
if (result != null) {
handleResult(result, record, message);
}
}
catch (Exception ex) {
throw new ListenerExecutionFailedException(createMessagingErrorMessage(// NOSONAR stack trace loss
"Listener error handler threw an exception for the incoming message",
message.getPayload()), ex);
}
}
else {
throw e;
}
}