原文地址: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. 实验一 C运行环境与最简单的程序设计

    实验一: #include<stdio.h> int main() {   int a1,a2;   int sum;   a1 =123;   a2 = 456;   sum = a1+ ...

  2. 基础篇:深入解析JAVA泛型和Type类型体系

    目录 1 JAVA的Type类型体系 2 泛型的概念 3 泛型类和泛型方法的示例 4 类型擦除 5 参数化类型ParameterizedType 6 泛型的继承 7 泛型变量TypeVariable ...

  3. Python实现好友生日提醒

    Python实现好友生日提醒  

  4. Consul 快速入门

    Consul是什么 Consul是一个服务网格(微服务间的 TCP/IP,负责服务之间的网络调用.限流.熔断和监控)解决方案,它是一个一个分布式的,高度可用的系统,而且开发使用都很简便.它提供了一个功 ...

  5. shell-批量修改文件名及扩展名多案例

    1. 功能描述如下表: 批量文件改名案例实战: 问题1:  创建测试数据 [root@1-241 tmp]# for i in `seq 6`;do touch stu_161226_${i}_fin ...

  6. 第四届58topcoder编程大赛--地图路径规划

    layout: post title: 第四届58topcoder编程大赛 subtitle: 58ACM catalog: true tags: - A* 算法 - C++ - 程序设计 问题及背景 ...

  7. 使用Python学习win32库进行内存读写

    前言: 上一周,在52的精华帖中,看到有位大佬用Python制作了鬼泣5的修改器,看完才知道,原来Python也可以对内存进行操作,出于对技术的好奇,看完以后,决定自己也尝试一下. 要用到的工具: C ...

  8. IDEA项目区模块文件变为红色解决办法

    解决方法 先检查文件格式是否为.java格式..class格式就不行. 选择file–>setting–>version Controller,然后把vcs选项选择为none

  9. 用算法去扫雷(go语言)

    最初的准备 首先得完成数据的录入,及从扫雷的程序读取界面数据成为我的算法可识别的数据 其次是设计扫雷的算法,及如何才能判断格子是雷或者可以点击鼠标左键和中键. 然后将步骤2的到的结果通过我的程序实现鼠 ...

  10. rabbitmq 交换机模式一 直连模式 direct

    代码 <?php require_once "./vendor/autoload.php"; use PhpAmqpLib\Connection\AMQPStreamConn ...