spring - 如何根据异常更改spring重试模板固定退避策略
问题描述
我正在使用 Spring 重试模板进行重试。
这是我的重试方法,这里我的重试间隔应该基于异常。例如,如果抛出 DataException,则应在 1000(1 秒)的时间间隔内重试,或者如果抛出 MQException,则应在 5000(5 秒)的时间间隔内重试。
如何根据异常更改 FixedBackOffPolicy 实例。
主要流程:
private void retryTest(){
retryTemplate.execute(context -> {
log.info("Processing request...");
retryTest1();
return true;
},
context -> {
log.info("Recovering request...");
return true;
});
}
private void retryTest1(){
throw new DataException("Data exception");
//throw new MQException("MQ Message exception");
}
重试模板初始化:
@Bean
public RetryTemplate retryTemplate() {
RetryTemplate retryTemplate = new RetryTemplate();
FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
fixedBackOffPolicy.setBackOffPeriod(1000L);
retryTemplate.setBackOffPolicy(new CustomBackOffPolicy()); // Custom backoff policy
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(5);
retryTemplate.setRetryPolicy(retryPolicy);
return retryTemplate;
}
public class CustomBackOffPolicy implements BackOffPolicy {
@Autowired
RetryTemplate retryTemplate;
@Override
public BackOffContext start(RetryContext retryContext) {
RetryPolicy retryPolicy = (RetryPolicy) retryContext;
return null;
}
@Override
public void backOff(BackOffContext backOffContext) throws BackOffInterruptedException {
try {
Thread.sleep(1000l);
} catch (InterruptedException var2) {
throw new BackOffInterruptedException("Thread interrupted while sleeping", var2);
}
}
解决方案
你需要一个自定义的BackOffPolicy
;RetryContext
您可以从方法中获取异常类型start()
。
ExceptionClassifierRetryPolicy
您可以使用与基于异常类型委托不同重试策略中使用的技术类似的技术。
推荐阅读
- node.js - 我可以使用范围使用 Nodejs mongoose 创建一个子类吗?
- linux - Linux组998,是什么意思?
- javascript - 无法读取未定义的属性“身份验证”
- google-chrome - 如何通过参数将自定义标头设置为 chrome 应用程序
- php - 如何优化查询以更快地运行(查询中的查询)
- excel - 如何使用linest函数计算多项式趋势线
- c - 链接错误未定义符号:__aeabi_uldivmod
- angular - 违反 UNIQUE KEY 约束实体框架
- python - 如何在python中解析/操作字符串值?
- firebase - Firestore,数组与文档列表