背景

最近做的一个需求,需要调用第三方接口。正常情况下,接口的响应是符合要求的,只有在网络抖动等极少数的情况下,会存在超时情况。因为是小概率事件,所以一次超时之后,进行一次重试操作应该就可以了。重试很简单,设定最多的重试次数,用一个循环来实现就好了。比如一次请求是这样:

@Controller
public class RetryController {
@Autowired
private RetryRequestService retryRequestService; public String doSth(String param) {
String result = retryRequestService.request(param);
return "响应是" + result;
}
}

改成重试三次,可以是这样:

@Controller
public class RetryController {
@Autowired
private RetryRequestService retryRequestService; public String doSth(String param) {
int count = 0;
String result = "";
while (count < 3) {
try {
result = retryRequestService.request(param);
break;
} catch (Exception e) {
count++;
}
}
return "响应是" + result;
}
}

如果请求接口超时(抛异常)了,那么会继续进入下一次循环重试。如果在超时时间内获取到了结果,那就结束循环,继续往下走。

用倒是能用,但是太丑了。不好看,还狠狠的侵入了原有的代码。所以有没有更优雅的方式呢?

快速接入spring-retry

这么常用的东西,肯定有轮子啊!于是spring-retry闪亮登场!

这是一个属于Spring全家桶的项目,也是被广泛运用的组件。在这里我默认你是个Spring Boot的项目了哈。

使用起来非常简单,只需要三步。

1、引入依赖

<!--springboot项目都不用引入版本号-->
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<!--还是需要aop的支持的-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>

2、在启动类上加注解@EnableRetry

此举是让你的Spring Boot项目支持spring-retry的重试功能。像这样:

@SpringBootApplication
@EnableRetry
@Slf4j
public class FastKindleApplication {
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = SpringApplication.run(FastKindleApplication.class, args);
String result = applicationContext.getBean(RetryController.class).doSth("");
log.info(result);
}
}

3、在需要重试的方法上加注解@Retryable

如上文所说,我们需要重试的方法是retryRequestService.request这个方法。那么我们就在这个方法上加@Retryable注解。如下:

@Service
@Slf4j
public class RetryRequestService {
@Autowired
private OtherSystemSpi otherSystemSpi; @Retryable(value = RuntimeException.class, maxAttempts = 5, backoff = @Backoff(delay = 100))
public String request(String param) {
double random = Math.random();
log.info("请求进来了,随机值为:" + random);
if (random > 0.1) {
throw new RuntimeException("超时");
}
return otherSystemSpi.request(param);
}
}

当然,我们这里写了个调皮的逻辑来模拟超时。如果随机值大于0.1则抛出一个RuntimeException异常。每次请求进来时都会输出日志。

我来解释一下@Retryable注解中的信息。

  • value = RuntimeException.class:是指方法抛出RuntimeException异常时,进行重试。这里可以指定你想要拦截的异常。
  • maxAttempts:是最大重试次数。如果不写,则是默认3次。
  • backoff = @Backoff(delay = 100):是指重试间隔。delay=100意味着下一次的重试,要等100毫秒之后才能执行。

我们来执行一下,可以看到日志输出:

2022-03-15 23:51:19.754  INFO 3343 --- [main] c.e.fastkindle.FastKindleApplication     : Started FastKindleApplication in 0.347 seconds (JVM running for 0.536)
2022-03-15 23:51:19.762 INFO 3343 --- [main] c.e.f.service.retry.RetryRequestService : 请求进来了,随机值为:0.11030214774098712
2022-03-15 23:51:19.867 INFO 3343 --- [main] c.e.f.service.retry.RetryRequestService : 请求进来了,随机值为:0.09624689154608002
2022-03-15 23:51:19.867 INFO 3343 --- [main] c.e.fastkindle.FastKindleApplication : 响应是mock

前两次的随机值都大于0.1,所以进行了重试,而且注意时间,都是间隔了大概100毫秒输出的日志。第三次的随机值小于0.1,就直接返回数据了。

我又试了几次,使五次请求的随机值都大于0.1,则结果是进行了五次请求,最后抛出了个异常。

2022-03-15 23:52:58.193  INFO 3449 --- [main] c.e.fastkindle.FastKindleApplication     : Started FastKindleApplication in 0.41 seconds (JVM running for 0.635)
2022-03-15 23:52:58.201 INFO 3449 --- [main] c.e.f.service.retry.RetryRequestService : 请求进来了,随机值为:0.5265644192525288
2022-03-15 23:52:58.303 INFO 3449 --- [main] c.e.f.service.retry.RetryRequestService : 请求进来了,随机值为:0.6343538744876432
2022-03-15 23:52:58.407 INFO 3449 --- [main] c.e.f.service.retry.RetryRequestService : 请求进来了,随机值为:0.5482463853575078
2022-03-15 23:52:58.511 INFO 3449 --- [main] c.e.f.service.retry.RetryRequestService : 请求进来了,随机值为:0.5624923285641071
2022-03-15 23:52:58.616 INFO 3449 --- [main] c.e.f.service.retry.RetryRequestService : 请求进来了,随机值为:0.305945622979098
Exception in thread "main" java.lang.RuntimeException: 超时
at com.esparks.fastkindle.service.retry.RetryRequestService.request(RetryRequestService.java:24)
at com.esparks.fastkindle.service.retry.RetryRequestService$$FastClassBySpringCGLIB$$50f0bdca.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)

总结

好啦,咱今天就介绍一下快速的接入spring-retry来实现重试功能。更详细的功能和实现原理,之后再详细介绍吧(又给自己挖了个坑)

用两行代码实现重试功能,spring-retry真是简单而优雅的更多相关文章

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

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

  2. Spring异常重试框架Spring Retry

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

  3. Spring Retry 重试

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

  4. Spring Retry 在SpringBoot 中的应用

    Spring Boot中使用Spring-Retry重试框架 Spring Retry提供了自动重新调用失败的操作的功能.这在错误可能是暂时的(例如瞬时网络故障)的情况下很有用. 从2.2.0版本开始 ...

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

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

  6. Spring框架中一个有用的小组件:Spring Retry

    1.概述 Spring Retry 是Spring框架中的一个组件, 它提供了自动重新调用失败操作的能力.这在错误可能是暂时发生的(如瞬时网络故障)的情况下很有帮助. 在本文中,我们将看到使用Spri ...

  7. Spring retry基本使用

    Spring retry基本使用 背景介绍 在实际工作过程中,重试是一个经常使用的手段.比如MQ发送消息失败,会采取重试手段,比如工程中使用RPC请求外部服务,可能因为网络 波动出现超时而采取重试手段 ...

  8. spring retry 使用

    1.  场景      系统方法调用时无状态的,同时因为网络原因,或者系统暂时故障,进行的重试 2. maven 依赖 <project xmlns="http://maven.apa ...

  9. Spring Retry

    最近组内准备将项目中原有的重试功能抽取出来重构为一个重试平台,由于对重试的功能要求比较高,采用了不少中间件和框架(jimdb,jproxy, Elastic-Job ,JMQ,Hbase, Disru ...

随机推荐

  1. SQL的多表查询(笛卡尔积原理)

    感谢大佬:https://blog.csdn.net/yang5726685/article/details/53538438 MySQL的多表查询(笛卡尔积原理) 先确定数据要用到哪些表. 将多个表 ...

  2. 通过bindservice方式调用服务方法里面的过程

    为什么要引入bindService:目的为了调用服务里面的方法 (1)定义一个服务 服务里面有一个方法需要Activity调用 (2)定义一个中间人对象(IBinder) 继承Binder (3)在o ...

  3. 自动循环滚动ScrollView

    // // SBCycleScrollView.h // SBCycleScrollView // // Created by luo.h on 15/7/12. // Copyright (c) 2 ...

  4. Solution -「LGR-087」「洛谷 P6860」象棋与马

    \(\mathcal{Description}\)   Link.   在一个 \(\mathbb R^2\) 的 \((0,0)\) 处有一颗棋子,对于参数 \(a,b\),若它当前坐标为 \((x ...

  5. Python中模块import的使用案例

    1 import test # 导入test模块 2 3 print(test.a) # 使用"模块.变量"调用模块中的变量 4 5 test.hi() # 使用"模块. ...

  6. windows上安装foremost

    做CTF题需要这工具来提取文件里的隐藏文件, 网上大部分是linux版本,之前好不容易找了一个exe文件结果还不能用.找了很长时间终于找到了: https://github.com/raddyfiy/ ...

  7. Wireshark教程之过滤器设置

    实验目的 1.工具介绍 2.主要应用 实验原理 1.网络管理员用来解决网络问题 2.网络安全工程师用来检测安全隐患 3.开发人员用来测试执行情况 4.学习网络协议 实验内容 1.抓取特定数据流 2.显 ...

  8. 网络测试技术——802.1X原理

    一.以太网优点缺点 1.以太网优点 (1)即插即用,简单快捷 (2)任何一台电脑只要接入网络便有访问网络资源的权限 2.以太网缺点 (1)缺乏安全认证机制(二层) (2)电脑接到交换机上就能访问网络 ...

  9. selenium+python自动化103-一闪而过的dialog如何定位

    前言 web页面操作的时候经常会遇到一闪而过的 dialog 消息,这些提示语一般只出现了几秒,过后元素节点就会在DOM中消失了. 本篇讲解下用chrome 浏览器如何定位一闪而过的 dialog 消 ...

  10. Anaconda Navigator:this application failed to start because it could not find or load ...windows in

    原因:在Anaconda的根目录下,有一个叫 qt.conf的文件,用记事本或者Notepad打开 该问题是这些路径错误导致的(比如你把Anaconda挪动了位置,导致这里边的路径还是原来的位置). ...