前言
失败了重来,重试策略在一定程度上提高了程序的健壮性。一些偶尔失败的程序,例如web服务的短暂网络故障,第三方设备故障,如果第一次运行失败,在接下来的重试能够保证程序运行成功,那么这段程序就应该引入重试策略,保证程序的健壮。
最简单的重试策略就是 while 循环,这里介绍 Spring 的重试策略其底层实现也是while循环,只是对其进行了封装,然后对外提供的一些比较简单的操作接口。Spring 提供了多种重试策略,可适用于多种场景,并且它优秀的代码设计能够容易的将其嵌入到待开发的系统中。
Maven 依赖
<!-- https://mvnrepository.com/artifact/org.springframework.retry/spring-retry -->
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>1.2.4.RELEASE</version>
</dependency>
简单的Demo
package com.test;
import org.junit.Test;
import org.springframework.retry.RetryCallback;
import org.springframework.retry.RetryContext;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.suppo