在调用第三方接口或者使用mq时,会出现网络抖动,链接超时等网络异常,因此须要重试。为了使处理更加健壮而且不太容易出现故障,后续的尝试操做,有时候会帮助失败的操做最后执行成功。例如,因为网络故障或数据库更新中的DeadLockLoserException致使Web服务或RMI服务的远程调用可能会在短暂等待后自行解决。 为了自动执行这些操做的重试,Spring Batch具备RetryOperations策略。不过该重试功能从Spring Batch 2.2.0版本中独立出来,变成了Spring Retry模块。java
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
复制代码
须要引入Spring-retry和aspectjweaver的依赖。git
@SpringBootApplication
@EnableRetry
public class SpringbootRetryApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootRetryApplication.class, args);
}
}
复制代码
入口类上开启retry的拦截,使用@EnableRetry
注解。github
@Service
public class PayService {
private Logger logger = LoggerFactory.getLogger(getClass());
private final int totalNum = 100000;
@Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 2000L, multiplier = 1.5))
public int minGoodsnum(int num) throws Exception {
logger.info("减库存开始" + LocalTime.now());
try {
int i = 1 / 0;
} catch (Exception e) {
logger.error("illegal");
}
if (num <= 0) {
throw new IllegalArgumentException("数量不对");
}
logger.info("减库存执行结束" + LocalTime.now());
return totalNum - num;
}
}
复制代码
@Retryable
的参数说明:web
@Backoff
,@Backoff
的value默认为1000L,咱们设置为2000L;multiplier(指定延迟倍数)默认为0,表示固定暂停1秒后进行重试,若是把multiplier设置为1.5,则第一次重试为2秒,第二次为3秒,第三次为4.5秒。@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootRetryApplicationTests {
@Autowired
private PayService payService;
@Test
public void payTest() throws Exception {
int store = payService.minGoodsnum(-1);
System.out.println("库存为:" + store);
}
}
复制代码
运行的控制台结果以下:spring
能够看到,三次以后抛出了IllegalArgumentException
异常。数据库
当重试耗尽时,RetryOperations能够将控制传递给另外一个回调,即RecoveryCallback。Spring-Retry还提供了@Recover注解,用于@Retryable重试失败后处理方法,此方法里的异常必定要是@Retryable方法里抛出的异常,不然不会调用这个方法。springboot
@Recover
public int recover(Exception e) {
logger.warn("减库存失败!!!" + LocalTime.now());
return totalNum;
}
复制代码
在Service中,加上如上的方法以后,进行测试。 微信
能够看到当三次重试执行完以后,会调用Recovery方法,也不会再次抛出异常。网络
本文主要讲了在Spring Boot项目中的Spring-Retry简单应用,主要是基于注解配置一些重试的策略,使用比较简单。主要的适用场景为在调用第三方接口或者使用mq时。因为会出现网络抖动,链接超时等网络异常,这时就须要重试。spring-boot
本文的代码: https://github.com/keets2012/Spring-Cloud_Samples/tree/master/springboot-retry