失败重试的策略(方法)
业务中往往会遇到失败重试的场景,如dubbo调用,默认3次重试,但是有些情况我们不能做重试操作,如被调用的接口不幂等。
正文
朴素方法
朴素就是代码一把梭,不考虑扩展性,重用性。
// 指定最大重试次数,成功就返回。
for (i = 0; i < retryTimes; i++) {
try {
return callback();
} catch (e) {
log.error(e);
}
}
Dubbo重试
先上代码:
Reference<xxxApi>.setRetryTimes(3);
xxxApi.doSomeInsert(1);
优势明显:内置!简洁!无侵入!
劣势明显:内置重试方法比较固定。
Spring Retry
本来考虑自己写一个重试框架的,发现spring-retry模块已经从Spring Batch项目中独立出来了,一个很小巧的模块,可以拿来就用。它使用了模板模式:
SimpleRetryPolicy policy = new SimpleRetryPolicy(5);
RetryTemplate template = new RetryTemplate();
template.setRetryPolicy(policy);
template.execute(new RetryCallback<Foo>() {
public Foo doWithRetry(RetryContext context) {
// 这里写业务代码
}
});
如果配合Spring AOP,代码可以更简洁:
@Service
class Service {
@Retryable(RemoteAccessException.class)
public service() {
// ... do something
}
}
优势巨大:
- 任意扩展重试策略(RetryTemplate),容易定义异步重试策略;
- 代码简洁,堪比dubbo内置;
劣势:对代码略有侵入性。