一:概述
  在调用第三方接口或者使用mq时,会出现网络抖动,连接超时等网络异常,所以需要重试。
  为了使处理更加健壮并且不太容易出现故障,后续的尝试操作,有时候会帮助失败的操作最后执行成功。
  例如,由于网络故障或数据库更新中的DeadLockLoserException导致Web服务或RMI服务的远程调用可能会在短暂等待后自行解决。 为了自动执行这些操作的重试,Spring Batch具有RetryOperations策略。不过该重试功能从Spring Batch 2.2.0版本中独立出来,变成了Spring Retry模块。
 
二:示例
1.pom
        <dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>

2.配置类

  只有启用@EnabelRetry才行,写在配置类或者启动类上都是可以的

package com.jun.web.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.retry.annotation.EnableRetry; @Configuration
@EnableRetry
public class RetryConfig {
}

3.服务类

  一般将其加到服务类上就行,服务类一般写主要逻辑

package com.jun.web.annotation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service; import java.time.LocalTime; @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;
} @Recover
public int recover(Exception e) {
logger.warn("减库存失败!!!" + LocalTime.now());
//记日志到数据库
return totalNum;
}
}

4.测试

package com.jun.web.annotation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
public class PayController {
@Autowired
private PayService payService; @GetMapping("/retry")
public String getNum() throws Exception {
int i = payService.minGoodsnum(-1);
System.out.println("===="+i);
return "succeess";
}
}

5.结果

2019-08-23 10:27:46.702 DEBUG 16036 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet        : GET "/retry", parameters={}
2019-08-23 10:27:46.702 DEBUG 16036 --- [nio-8080-exec-5] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to public java.lang.String com.jun.web.annotation.PayController.getNum() throws java.lang.Exception
2019-08-23 10:27:46.703 INFO 16036 --- [nio-8080-exec-5] com.jun.web.annotation.PayService : 减库存开始10:27:46.703
2019-08-23 10:27:46.703 ERROR 16036 --- [nio-8080-exec-5] com.jun.web.annotation.PayService : illegal
2019-08-23 10:27:48.703 INFO 16036 --- [nio-8080-exec-5] com.jun.web.annotation.PayService : 减库存开始10:27:48.703
2019-08-23 10:27:48.703 ERROR 16036 --- [nio-8080-exec-5] com.jun.web.annotation.PayService : illegal
2019-08-23 10:27:51.704 INFO 16036 --- [nio-8080-exec-5] com.jun.web.annotation.PayService : 减库存开始10:27:51.704
2019-08-23 10:27:51.704 ERROR 16036 --- [nio-8080-exec-5] com.jun.web.annotation.PayService : illegal
2019-08-23 10:27:51.704 WARN 16036 --- [nio-8080-exec-5] com.jun.web.annotation.PayService : 减库存失败!!!10:27:51.704
====100000
2019-08-23 10:27:51.704 DEBUG 16036 --- [nio-8080-exec-5] m.m.a.RequestResponseBodyMethodProcessor : Using 'text/html', given [text/html, application/xhtml+xml, image/webp, image/apng, application/signed-exchange;v=b3, application/xml;q=0.9, */*;q=0.8] and supported [text/plain, */*, text/plain, */*, application/json, application/*+json, application/json, application/*+json]
2019-08-23 10:27:51.704 DEBUG 16036 --- [nio-8080-exec-5] m.m.a.RequestResponseBodyMethodProcessor : Writing ["succeess"]
2019-08-23 10:27:51.705 DEBUG 16036 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : Completed 200 OK
2019-08-23 10:27:51.714 DEBUG 16036 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : GET "/favicon.ico", parameters={}
2019-08-23 10:27:51.715 DEBUG 16036 --- [nio-8080-exec-6] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler [class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/], ServletContext resource [/], class path resource []]
2019-08-23 10:27:51.718 DEBUG 16036 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : Completed 200 OK

三:说明

1.@Retryable参数的意思说明

  • value:抛出指定异常才会重试
  • include:和value一样,默认为空,当exclude也为空时,默认所以异常
  • exclude:指定不处理的异常
  • maxAttempts:最大重试次数,默认3次
  • backoff:重试等待策略,默认使用@Backoff@Backoff的value默认为1000L,我们设置为2000L;multiplier(指定延迟倍数)默认为0,表示固定暂停1秒后进行重试,如果把multiplier设置为1.5,则第一次重试为2秒,第二次为3秒,第三次为4.5秒。

2.Recover注解

  

  当重试耗尽时,RetryOperations可以将控制传递给另一个回调,即RecoveryCallback。Spring-Retry还提供了@Recover注解,用于@Retryable重试失败后处理方法,此方法里的异常一定要是@Retryable方法里抛出的异常,否则不会调用这个方法。
  从上面的结果上可以看出来。

四:注意事项

1.注意
  使用了@Retryable的方法在本类中使用没有效果,只有在其他类中使用@Autowired注入或者@Bean才能生效
  要触发@Recover方法,@Retryable方法不能存在返回值,只能是void
  非幂等下慎用
  使用@Retryable的方法里不能使用try  catch包裹,要在方法上抛出异常,不然不会触发

最新文章

  1. 关于SubSonic3.0未处理InvalidOperationException异常(关键字TOP附近有语法错误)的处理
  2. How to inspect who is caller of func and who is the class of instance
  3. JDBC连接数据库(SQLServer和MySQL)配置总结
  4. swift 异步加载图片(第三方框架ImageLoader)
  5. tomcat-8.0
  6. 分析MySQL慢日志(转)
  7. java 的 (PO,VO,TO,BO,DAO,POJO) 解释
  8. lego blocks
  9. iOS开发——实战OC篇&amp;环境搭建之StoryBoard(玩转UINavigationController与UITabBarController)
  10. python 基础——装饰器
  11. php yii多表查询
  12. JS 打字机效果
  13. android实现对导航Tab设置下划线选中效果
  14. 虚拟云主机创建多个站点方法(.htaccess实现)
  15. 消息队列RabbitMq、ActiveMq、ZeroMq、kafka之间的比较
  16. BZOJ2209 [Jsoi2011]括号序列 splay
  17. 利用Apache AXIS 1 发布WebService
  18. win10,配置python3.6,虚拟环境
  19. gaia 开源多语言的pipeline 平台
  20. 解决Winform程序在不同分辨率系统下界面混乱

热门文章

  1. 【python】文件操作
  2. MySQL优化整理
  3. MySQL/MariaDB数据库的MHA实现高可用实战
  4. selenium与webdriver驱动与firefox、 chrome匹配版本
  5. python图像处理库Pillow基本使用方法
  6. myslq数据库用union all查询出现 #1271 - Illegal mix of collations for operation &#39;UNION&#39;
  7. 《exception》第九次团队作业:Beta冲刺与验收准备(第一天)
  8. modbus-poll和modbus-slave工具的学习使用——环境搭建
  9. Windows 2008R2 安装PostgreSQL 11.6
  10. velero 备份、迁移 kubernetes 应用以及持久化数据卷