我正在考虑将 @SendTo
注释与 @KafkaListener
注释一起使用。我将收到一条消息,将进行最少的计算,这将不超过一个方法调用。不过,该方法有可能引发异常。在这种情况下,我将抛出然后捕获异常(想要捕获它)。在这种情况下,是否可以不将对象/字符串转发到主题,因为在我的系统中发生的异常应该是足够的理由,即对象/字符串格式错误且不适合进一步使用?
编辑-
所以我在想类似于@cacheable-除非的东西?
提前谢谢您!
最佳答案
我认为@Cacheable.unless()
在这里有点误导:
/**
* Spring Expression Language (SpEL) expression used to veto method caching.
* <p>Unlike {@link #condition}, this expression is evaluated after the method
* has been called and can therefore refer to the {@code result}.
您会看到它是针对方法结果执行的。在您的情况下,您正在讨论异常,因此您需要考虑使用 @KafkaListener.errorHandler()
,其工作原理如下:
catch (ListenerExecutionFailedException e) {
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(
"Listener error handler threw an exception for the incoming message",
message.getPayload()), ex);
}
}
else {
throw e;
}
}
因此,在您的情况下,不要将错误消息传播到 @SendTo
,您应该只从 KafkaListenerErrorHandler.handleError()
返回任何内容。
关于java - 在 @KafkaListener 上使用 @SendTo 有条件转发消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48455485/