【发布时间】:2019-10-17 11:24:31
【问题描述】:
上下文:
我正在使用 spring-retry 来重试 restTemplate 调用。
restTemplate 调用是从 kafka 侦听器调用的。 kafka 监听器也被配置为错误重试(如果在这个过程中抛出任何异常,不仅是 restTemplate 调用)。
目标:
当错误来自已用尽的重试模板时,我想防止 kafka 重试。
实际行为:
当 retryTemplate 用尽所有重试时,会抛出原始异常。从而阻止我确定错误是否由 retryTemplate 重试。
期望的行为:
当 retryTemplate 耗尽所有重试时,将原始异常包装在 RetryExhaustedException 中,这将允许我将其从 kafka 重试中列入黑名单。
问题:
我该怎么做这样的事情?
谢谢
编辑
重试模板配置:
RetryTemplate retryTemplate = new RetryTemplate();
FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
backOffPolicy.setBackOffPeriod(1000);
retryTemplate.setBackOffPolicy(backOffPolicy);
Map<Class<? extends Throwable>, Boolean> retryableExceptions = new HashMap<>();
retryableExceptions.put(FunctionalException.class, false);
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(3, retryableExceptions, true, true);
retryTemplate.setRetryPolicy(retryPolicy);
retryTemplate.setThrowLastExceptionOnExhausted(false);
卡夫卡错误处理程序
public class DefaultErrorHandler implements ErrorHandler {
@Override
public void handle(Exception thrownException, ConsumerRecord<?, ?> data) {
Throwable exception = Optional.ofNullable(thrownException.getCause()).orElse(thrownException);
// TODO if exception as been retried in a RetryTemplate, stop it to prevent rollback and send it to a DLQ
// else rethrow exception, it will be rollback and handled by AfterRollbackProcessor to be retried
throw new KafkaException("Could not handle exception", thrownException);
}
}
监听卡夫卡:
@KafkaListener
public void onMessage(ConsumerRecord<String, String> record) {
retryTemplate.execute((args) -> {
throw new RuntimeException("Should be catched by ErrorHandler to prevent rollback");
}
throw new RuntimeException("Should be retried by afterRollbackProcessor");
}
【问题讨论】:
标签: spring-retry