[英]Log the exceptions thrown in spring kafka listener
我们使用的是 Spring kafka 2.7 非阻塞重试机制。 我们想记录在@KafkaListener 方法中使用数据时抛出的错误。
例如: https : //github.com/spring-projects/spring-kafka/blob/main/samples/sample-04/src/main/java/com/example/Application.java
在上面的例子中我们可以看到,抛出了一个 RuntimeException。 但是该异常不会被记录下来,而是我们将在异常之后将Seek 设置为当前 .... 。
// our configuration
@Bean
public ConcurrentKafkaListenerContainerFactory<String, Object> kafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, Object> factory
= new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory());
return factory;
}
@Bean
public RetryTopicConfiguration retryTopicConfiguration(KafkaTemplate<String, Object> template) {
List<Class<? extends Throwable>> throwableList = Arrays.asList(IllegalArgumentException.class,
IllegalAccessException.class);
return RetryTopicConfigurationBuilder
.newInstance()
.dltHandlerMethod(XYZ.class, "xyz")
.exponentialBackoff(delayMs, backoffMultiplier, maxIntervalInMs)
.maxAttempts(retryAttempt)
.notRetryOn(throwableList)
.doNotAutoCreateRetryTopics()
.listenerFactory(kafkaListenerContainerFactory())
.setTopicSuffixingStrategy(TopicSuffixingStrategy.SUFFIX_WITH_INDEX_VALUE)
.create(template);
}
您可以使用RecordInterceptor
。
@Bean
RecordInterceptor<String, String> interceptor(ConcurrentKafkaListenerContainerFactory<String, String> factory) {
RecordInterceptor<String, String> inter = new RecordInterceptor<String, String>() {
@Override
@Nullable
public ConsumerRecord<String, String> intercept(ConsumerRecord<String, String> record) {
return record;
}
@Override
public void failure(ConsumerRecord<String, String> record, Exception exception,
Consumer<String, String> consumer) {
logger.error("Record failed " + ListenerUtils.recordToString(record, true), exception);
}
};
factory.setRecordInterceptor(inter);
return inter;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.