原文地址:https://www.jianshu.com/p/ee02d6125113

需求背景:

有些时候我们再调用一些第三方服务的时候,从第三方那边拉数据。

但是第三方服务不是100%稳定的,有些时候会抽风一下,导致我们的调用失败,整个调用链就失败。整个时候需要触发重试,而且不是一直死循环重试,因为第三方服务器不稳定的情况下一直循环也是大概率失败,而是应该每隔一段时间重试一次,例如第二次重试是30s后,第三次重试是60s后,第四次重试是120s后如此类推。

这个时候我就想到到spring-retry,下面是spring-retry的使用教学

一、新建springboot工程

二、引入依赖

org.springframework.boot
spring-boot-starter-web

org.springframework.retry
spring-retry

org.aspectj
aspectjweaver
1.9.2

org.springframework.boot
spring-boot-starter-test
test

org.junit.vintage
junit-vintage-engine

三、编写测试类

@Component

@EnableRetry

public class RetryService {

@Retryable(maxAttempts = 5,backoff = @Backoff(multiplier = 2,value = 2000L,maxDelay = 10000L))
public void retry(){
System.out.println(new Date());
throw new RuntimeException("retry异常");
}

}

其中要在测试类上面打注解@EnableRetry,测试方法上面打注册@Retryable,'@Retryable'注解中,maxAttempts是最大尝试次数,backoff是重试策略,value 是初始重试间隔毫秒数,默认是3000l,multiplier是重试乘数,例如第一次是3000l,第二次是3000lmultiplier,第三次是3000lmultiplier2如此类推,maxDelay是最大延迟毫秒数,如果3000lmultiplier*n>maxDelay,延时毫秒数会用maxDelay。

四、运行单元测试类,效果如下

image.png

延迟时间分别是2、4、8、10s。

实现原理

我们可以通过写一个自己的注解去实现同样的逻辑

@MyBackoff注解类

@Target({ElementType.TYPE})

@Retention(RetentionPolicy.RUNTIME)

public @interface MyBackoff {

long value() default 1000L;

long maxDelay() default 0L;

double multiplier() default 0.0D;

}

@MyRetryable注解类

@Target({ElementType.TYPE})

@Retention(RetentionPolicy.RUNTIME)

public @interface MyBackoff {

long value() default 1000L;

long maxDelay() default 0L;

double multiplier() default 0.0D;

}

aop切面类

@Component

@Aspect

public class Aop {

protected org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(this.getClass());

@Pointcut("@annotation(com.eujian.springretry.myanno.MyRetryable)")
public void pointCutR() {
}
/**
* 埋点拦截器具体实现
*/
@Around("pointCutR()")
public Object methodRHandler(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
Method targetMethod = methodSignature.getMethod();
MyRetryable myRetryable = targetMethod.getAnnotation(MyRetryable.class);
MyBackoff backoff = myRetryable.backoff();
int maxAttempts = myRetryable.maxAttempts();
long sleepSecond = backoff.value();
double multiplier = backoff.multiplier();
if(multiplier<=0){
multiplier = 1;
}
Exception ex = null;
int retryCount = 1;
do{
try { Object proceed = joinPoint.proceed();
return proceed;
}catch (Exception e){
logger.info("睡眠{}毫秒",sleepSecond);
Thread.sleep(sleepSecond);
retryCount++;
sleepSecond = (long)(multiplier)*sleepSecond;
if(sleepSecond>backoff.maxDelay()){
sleepSecond = backoff.maxDelay();
logger.info("睡眠时间太长,改成{}毫秒",sleepSecond);
}
ex = e; }
}while (retryCount<maxAttempts); throw ex;
}

}

运行测试类效果

用spring-retry注解自动触发重试方法的更多相关文章

  1. Spring基于注解自动装配

    前面我们介绍Spring IoC装载的时候,使用XML配置这种方法来装配Bean,这种方法可以很直观的看到每个Bean的依赖,但缺点也很明显:写起来非常繁琐,每增加一个组件,就必须把新的Bean配置到 ...

  2. Spring @Autowired 注解自动注入流程是怎么样?

    面试中碰到面试官问:"Spring 注解是如果工作的?",当前我一惊,完了这不触及到我的知识误区了吗?,还好我机智,灵机一动回了句:Spring 注解的工作流程倒还没有看到,但是我 ...

  3. spring retry注解

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20 ...

  4. with一个对象,自动触发__enter__方法

    class Foo(object): def __init__(self): pass def __enter__(self): print("__enter__") def __ ...

  5. Spring Retry 重试

    重试的使用场景比较多,比如调用远程服务时,由于网络或者服务端响应慢导致调用超时,此时可以多重试几次.用定时任务也可以实现重试的效果,但比较麻烦,用Spring Retry的话一个注解搞定所有.话不多说 ...

  6. Spring retry实践

    在开发中,重试是一个经常使用的手段.比如MQ发送消息失败,会采取重试手段,比如工程中使用RPC请求外部服务,可能因为网络波动出现超时而采取重试手段......可以看见重试操作是非常常见的一种处理问题, ...

  7. Spring异常重试框架Spring Retry

    Spring Retry支持集成到Spring或者Spring Boot项目中,而它支持AOP的切面注入写法,所以在引入时必须引入aspectjweaver.jar包. 快速集成的代码样例: @Con ...

  8. 异常重试框架Spring Retry实践

    前期准备在Maven项目中添加Spring Retry和切面的依赖 POM: <!-- Spring Retry --> <dependency> <groupId> ...

  9. 自己动手实践 spring retry 重试框架

    前序 马上过年了,预祝大家,新年快乐,少写bug 什么是spring retry? spring retry是从spring batch独立出来的一个能功能,主要实现了重试和熔断. 什么时候用? 远程 ...

随机推荐

  1. 简单区间dp

    题目链接 对于基本区间dp,设dp[l][r]是区间l到r的最大价值. 我们可以枚举区间的长度,在枚举左端点,判断即可. 当右端点大于n,就break. dp[l][r]=max(dp[l+1][r] ...

  2. 多测师_高级讲师肖sir讲解html中 Button跳转连接方法归纳

    第一种方法: 1.1<a href="http://www.baidu.com">   <input type="button" name=& ...

  3. 记录一次源码扩展案列——FastJson自定义反序列化ValueMutator

    背景:曾经遇到一个很麻烦的事情,就是一个json串中有很多占位符,需要替换成特定文案.如果将json转换成对象后,在一个一个属性去转换的话就出出现很多冗余代码,不美观也不是很实用. 而且也不能提前在j ...

  4. ubuntu vi编辑器上下左右为ABCD的解决办法

    这个ubuntu系统自带的vi版本太老导致的,所以解决办法就是安装新版的vi编辑器: 首先卸载旧版本的vi编辑器: $sudo apt-get remove vim-common 然后安装新版的vi: ...

  5. 后羿:我射箭了快上—用MotionLayout实现王者荣耀团战

    前言 昨晚跟往常一样,饭后开了一局王者荣耀,前中期基本焦灼,到了后期一波决定胜负的时候,我果断射箭,射中对面,配合队友直接秒杀,打赢团战一波推完基地.那叫一个精彩,队友都发出了666666的称赞,我酷 ...

  6. 某次burp抓包出错的解决办法

    前些日子同事发微信问我一个问题 没听懂他说的没回显是啥意思,于是叫他把站发给我. 浏览器不挂burp代理能正常打开,挂上burp代理以后浏览器显示连接超时 首先测试burp能抓其他的包应不是这个原因 ...

  7. C# 面试前的准备_基础知识点的回顾_01

    本系列本章来至于http://www.cnblogs.com/LionelMessi/p/4311931.html 1.try{} 里面有个Return语句,那么紧跟try后面的Finally{}会不 ...

  8. Linux命令行扩展和被括起来的集合

    命令行扩展:`` 和 $() 单引号'' 双引号"" 反向单引号`` 在很多场景下效果不同 [root@centos8 ~]#echo "echo $HOSTNAME&q ...

  9. 微信小程序分类的实现

    微信小程序的分类功能思路 实现思路 1.把屏幕当成一个固定的盒子,然后把盒子分成两边,并让盒子的每一边都能够滚动. 2.通过将左侧边栏元素的id和右边内容的categoryId进行匹配,渲染展示相同i ...

  10. unittest学习

    unittest的四大特点 TestCase:测试用例.所有的用例都是直接继承与UnitTest.TestCase类. TestFixture:测试固件.setUp和tearDown分别作为前置条件和 ...