上文我们在学习容错机制理论中,我们发现其中有一种处理手段为failback故障自动恢复
,Spring-Retry即为failback的实现中间件,下面我们就来开始学习Spring-Retry
基本框架例子
框架介绍
- RetryTemplate,重试模板,是进入spring-retry框架的整体流程入口
- RetryCallback,该接口封装了业务代码,且failback后,会再次调用RetryCallback接口
- RetryPolicy,重试策略,描述将以什么样的方式调用RetryCallback接口
使用Spring Retry例子
public class RetryTemplateDemo {
/**
* 业务代码
*/
private static String business() throws Exception {
System.out.println("begin...");
if (true) {
throw new Exception();
}
System.out.println("end...");
return "success";
}
public static void main(String[] args) throws Exception {
RetryTemplate template = new RetryTemplate();
SimpleRetryPolicy policy = new SimpleRetryPolicy(3);
template.setRetryPolicy(policy);
RetryCallback<String, Exception> retryCallback = (context) -> {
return business();
};
String result = template.execute(retryCallback);
System.out.println(result);
}
}
测试结果
22:24:53.746 [main] DEBUG org.springframework.retry.support.RetryTemplate - Retry: count=0
begin...
22:24:53.751 [main] DEBUG org.springframework.retry.support.RetryTemplate - Checking for rethrow: count=1
22:24:53.751 [main] DEBUG org.springframework.retry.support.RetryTemplate - Retry: count=1
begin...
22:24:53.751 [main] DEBUG org.springframework.retry.support.RetryTemplate - Checking for rethrow: count=2
22:24:53.751 [main] DEBUG org.springframework.retry.support.RetryTemplate - Retry: count=2
begin...
22:24:53.751 [main] DEBUG org.springframework.retry.support.RetryTemplate - Checking for rethrow: count=3
22:24:53.751 [main] DEBUG org.springframework.retry.support.RetryTemplate - Retry failed last attempt: count=3
Exception in thread "main" java.lang.Exception
at priv.dengjili.spring.retry.demo.test.RetryTemplateDemo5.business(RetryTemplateDemo5.java:44)
at priv.dengjili.spring.retry.demo.test.RetryTemplateDemo5.lambda$0(RetryTemplateDemo5.java:33)
at priv.dengjili.spring.retry.demo.test.RetryTemplateDemo5$$Lambda$1/1221555852.doWithRetry(Unknown Source)
at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:329)
at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:209)
at priv.dengjili.spring.retry.demo.test.RetryTemplateDemo5.main(RetryTemplateDemo5.java:35)
通过结果我们可以看出,原业务代码会抛出异常,同时也设置了重试策略SimpleRetryPolicy,重试次数为3次,从测试结果我们可以看出,结果一致
RetryPolicy提供了其他策略实现:
- NeverRetryPolicy:只允许调用RetryCallback一次,不允许重试;
- AlwaysRetryPolicy:允许无限重试,直到成功,此方式逻辑不当会导致死循环;
- SimpleRetryPolicy:固定次数重试策略,默认重试最大次数为3次,RetryTemplate默认使用的策略;
- TimeoutRetryPolicy:超时时间重试策略,默认超时时间为1秒,在指定的超时时间内允许重试;
- CircuitBreakerRetryPolicy:有熔断功能的重试策略,需设置3个参数openTimeout、resetTimeout和delegate;
- CompositeRetryPolicy:组合重试策略,有两种组合方式,乐观组合重试策略是指只要有一个策略允许重试即可以,悲观组合重试策略是指只要有一个策略不允许重试即可以,但不管哪种组合方式,组合中的每一个策略都会执行。
详细使用例子参考官网:https://github.com/spring-projects/spring-retry
RecoveryCallback 恢复策略
- RecoveryCallback ,当我们进行所有重试,依然失败后,提供一个恢复的补偿方法
public class RetryTemplateDemo {
/**
* 业务代码
*/
private static String business() throws Exception {
System.out.println("begin...");
if (true) {
throw new Exception();
}
System.out.println("end...");
return "success";
}
public static void main(String[] args) throws Exception {
RetryTemplate template = new RetryTemplate();
SimpleRetryPolicy policy = new SimpleRetryPolicy(3);
template.setRetryPolicy(policy);
RetryCallback<String, Exception> retryCallback = (context) -> {
return business();
};
RecoveryCallback<String> recoveryCallback = (context) -> {
return "default_sucesss";
};
String result = template.execute(retryCallback, recoveryCallback);
System.out.println(result);
}
}
测试结果
22:45:37.823 [main] DEBUG org.springframework.retry.support.RetryTemplate - Retry: count=0
begin...
22:45:37.826 [main] DEBUG org.springframework.retry.support.RetryTemplate - Checking for rethrow: count=1
22:45:37.826 [main] DEBUG org.springframework.retry.support.RetryTemplate - Retry: count=1
begin...
22:45:37.827 [main] DEBUG org.springframework.retry.support.RetryTemplate - Checking for rethrow: count=2
22:45:37.827 [main] DEBUG org.springframework.retry.support.RetryTemplate - Retry: count=2
begin...
22:45:37.827 [main] DEBUG org.springframework.retry.support.RetryTemplate - Checking for rethrow: count=3
22:45:37.827 [main] DEBUG org.springframework.retry.support.RetryTemplate - Retry failed last attempt: count=3
default_sucesss
通过结果我们可以看出,原业务代码会抛出异常,同时也设置了重试策略SimpleRetryPolicy,重试次数为3次,依然失败,最后执行RecoveryCallback接口方法,结果一致
有状态的重试
有没状态如何理解,HTTP是无状态的,即两次调用接口之间不存在任何关系或者影响,有状态意味着调用之间有影响。
比如是由于事务资源导致的失败,那么多次调用可能会出现数据问题,那么将不能够进行重试,立刻上报异常。Spring-Retry提供了RetryState对象,这里举例说明一下即可
public class RetryTemplateDemo5 {
/**
* 业务代码
*/
private static String business() throws Exception {
System.out.println("begin...");
if (true) {
throw new Exception();
}
System.out.println("end...");
return "success";
}
public static void main(String[] args) throws Exception {
RetryTemplate template = new RetryTemplate();
SimpleRetryPolicy policy = new SimpleRetryPolicy(3);
template.setRetryPolicy(policy);
RetryCallback<String, Exception> retryCallback = (context) -> {
return business();
};
RecoveryCallback<String> recoveryCallback = (context) -> {
return "default_sucesss";
};
RetryState state = new DefaultRetryState("unique call");
String result = template.execute(retryCallback, recoveryCallback, state);
System.out.println(result);
}
}
测试结果
22:56:59.883 [main] DEBUG org.springframework.retry.support.RetryTemplate - Retry: count=0
begin...
22:56:59.887 [main] DEBUG org.springframework.retry.support.RetryTemplate - Checking for rethrow: count=1
22:56:59.887 [main] DEBUG org.springframework.retry.support.RetryTemplate - Rethrow in retry for policy: count=1
Exception in thread "main" java.lang.Exception
at priv.dengjili.spring.retry.demo.test.RetryTemplateDemo5.business(RetryTemplateDemo5.java:30)
at priv.dengjili.spring.retry.demo.test.RetryTemplateDemo5.lambda$0(RetryTemplateDemo5.java:41)
at priv.dengjili.spring.retry.demo.test.RetryTemplateDemo5$$Lambda$1/2104457164.doWithRetry(Unknown Source)
at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:329)
at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:255)
at priv.dengjili.spring.retry.demo.test.RetryTemplateDemo5.main(RetryTemplateDemo5.java:47)
测试与预期一致
RetryListener监听器
提供了三个监听的地方
public class RetryTemplateDemo5 {
/**
* 业务代码
*/
private static String business() throws Exception {
System.out.println("begin...");
if (true) {
throw new Exception();
}
System.out.println("end...");
return "success";
}
public static void main(String[] args) throws Exception {
RetryTemplate template = new RetryTemplate();
SimpleRetryPolicy policy = new SimpleRetryPolicy(3);
template.setRetryPolicy(policy);
RetryCallback<String, Exception> retryCallback = (context) -> {
return business();
};
RecoveryCallback<String> recoveryCallback = (context) -> {
return "default_sucesss";
};
RetryListener listener = new RetryListener() {
@Override
public <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback) {
System.out.println("open");
// 必须返回true,不然结束了
return true;
}
@Override
public <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback,
Throwable throwable) {
System.out.println("close");
}
@Override
public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback,
Throwable throwable) {
System.out.println("onError");
}};
// 可设置多个RetryListener
template.setListeners(new RetryListener[] {listener});
String result = template.execute(retryCallback, recoveryCallback);
System.out.println(result);
}
}
测试结果
open
23:08:58.601 [main] DEBUG org.springframework.retry.support.RetryTemplate - Retry: count=0
begin...
onError
23:08:58.605 [main] DEBUG org.springframework.retry.support.RetryTemplate - Checking for rethrow: count=1
23:08:58.606 [main] DEBUG org.springframework.retry.support.RetryTemplate - Retry: count=1
begin...
onError
23:08:58.606 [main] DEBUG org.springframework.retry.support.RetryTemplate - Checking for rethrow: count=2
23:08:58.606 [main] DEBUG org.springframework.retry.support.RetryTemplate - Retry: count=2
begin...
onError
23:08:58.606 [main] DEBUG org.springframework.retry.support.RetryTemplate - Checking for rethrow: count=3
23:08:58.606 [main] DEBUG org.springframework.retry.support.RetryTemplate - Retry failed last attempt: count=3
close
default_sucesss
测试与预期一致
其他说明
从1.3版开始,RetryTemplate的更简单配置也可以使用,如下所示:
RetryTemplate.builder()
.maxAttempts(10)
.exponentialBackoff(100, 2, 10000)
.retryOn(IOException.class)
.traversingCauses()
.build();
RetryTemplate.builder()
.fixedBackoff(10)
.withinMillis(3000)
.build();
RetryTemplate.builder()
.infiniteRetry()
.retryOn(IOException.class)
.uniformRandomBackoff(1000, 3000)
.build();
或者使用声明式编程,注解方式,如下所示:
eg1:
@Configuration
@EnableRetry
public class Application {
@Bean
public Service service() {
return new Service();
}
@Bean public RetryListener retryListener1() {
return new RetryListener() {...}
}
@Bean public RetryListener retryListener2() {
return new RetryListener() {...}
}
}
@Service
class Service {
@Retryable(RemoteAccessException.class)
public service() {
// ... do something
}
}
eg2:
@Service
class Service {
@Retryable(maxAttempts=12, backoff=@Backoff(delay=100, maxDelay=500))
public service() {
// ... do something
}
}
eg3:
@Service
class Service {
@Retryable(recover = "service1Recover", value = RemoteAccessException.class)
public void service1(String str1, String str2) {
// ... do something
}
@Retryable(recover = "service2Recover", value = RemoteAccessException.class)
public void service2(String str1, String str2) {
// ... do something
}
@Recover
public void service1Recover(RemoteAccessException e, String str1, String str2) {
// ... error handling making use of original args if required
}
@Recover
public void service2Recover(RemoteAccessException e, String str1, String str2) {
// ... error handling making use of original args if required
}
}
源码导读
以上是我通过阅读Spring-Retry源码整理出来的,源代码目录https://github.com/spring-projects/spring-retry
核心代码入口:org.springframework.retry.support.RetryTemplate
方法doExecute
参考
https://blog.csdn.net/u012731081/article/details/78892897