精讲RestTemplate第8篇-请求失败自动重试机制
本文是精讲RestTemplate第8篇,前篇的blog访问地址如下:
- 精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用
- 精讲RestTemplate第2篇-多种底层HTTP客户端类库的切换
- 精讲RestTemplate第3篇-GET请求使用方法详解
- 精讲RestTemplate第4篇-POST请求方法使用详解
- 精讲RestTemplate第5篇-DELETE、PUT等请求方法使用详解
- 精讲RestTemplate第6篇-文件上传下载与大文件流式下载
- 精讲RestTemplate第7篇-自定义请求失败异常处理
在上一节我们为大家介绍了,当RestTemplate发起远程请求异常时的自定义处理方法,我们可以通过自定义的方式解析出HTTP Status Code状态码,然后根据状态码和业务需求决定程序下一步该如何处理。
本节为大家介绍另外一种通用的异常的处理机制:那就是自动重试。也就是说,在RestTemplate发送请求得到非200状态结果的时候,间隔一定的时间再次发送n次请求。n次请求都失败之后,最后抛出HttpClientErrorException。
在开始本节代码之前,将上一节的RestTemplate自定义异常处理的代码注释掉,否则自动重试机制不会生效。如下(参考上一节代码):
//restTemplate.setErrorHandler(new MyRestErrorHandler());
一、Spring Retry配置生效
通过maven坐标引入spring-retry,spring-retry的实现依赖于面向切面编程,所以引入aspectjweaver。以下配置过程都是基于Spring Boot应用。
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>1.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
在Spring Boot 应用入口启动类,也就是配置类的上面加上@SpringRetry注解,表示让重试机制生效。

二、使用案例
- 写一个模拟的业务类RetryService ,在其里面注入RestTemplate 。RestTemplate 实例化Bean配置参考: 《精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用》 和 《精讲RestTemplate第2篇-多种底层HTTP客户端类库的切换》 进行实现。
- 将正确的请求服务地址由“/posts/1”改成“/postss/1”。服务不存在所以抛出404异常,是为了触发重试机制。
@Service
public class RetryService {
@Resource
private RestTemplate restTemplate;
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Retryable(value = RestClientException.class, maxAttempts = 3,
backoff = @Backoff(delay = 5000L,multiplier = 2))
public HttpStatus testEntity() {
System.out.println("发起远程API请求:" + DATE_TIME_FORMATTER.format(LocalDateTime.now()));
String url = "http://jsonplaceholder.typicode.com/postss/1";
ResponseEntity<String> responseEntity
= restTemplate.getForEntity(url, String.class);
return responseEntity.getStatusCode(); // 获取响应码
}
}
@Retryable注解的方法在发生异常时会重试,参数说明:- value:当指定异常发生时会进行重试 ,HttpClientErrorException是RestClientException的子类。
- include:和value一样,默认空。如果 exclude也为空时,所有异常都重试
- exclude:指定异常不重试,默认空。如果 include也为空时,所有异常都重试
- maxAttemps:最大重试次数,默认3
- backoff:重试等待策略,默认空
@Backoff注解为重试等待的策略,参数说明:- delay:指定重试的延时时间,默认为1000毫秒
- multiplier:指定延迟的倍数,比如设置delay=5000,multiplier=2时,第一次重试为5秒后,第二次为10(5x2)秒,第三次为20(10x2)秒。
写一个测试的RetryController 对RetryService 的testEntity方法进行调用
@RestController
public class RetryController {
@Resource
private RetryService retryService;
@GetMapping("/retry")
public HttpStatus test() {
return retryService.testEntity();
}
}
三、测试结果
向 http://localhost:8080/retry 发起请求,结果如下:

从结果可以看出:
- 第一次请求失败之后,延迟5秒后重试
- 第二次请求失败之后,延迟10秒后重试
- 第三次请求失败之后,抛出异常
欢迎关注我的博客,里面有很多精品合集
- 本文转载注明出处(必须带连接,不能只转文字):字母哥博客。
觉得对您有帮助的话,帮我点赞、分享!您的支持是我不竭的创作动力! 。另外,笔者最近一段时间输出了如下的精品内容,期待您的关注。
- 《手摸手教你学Spring Boot2.0》
- 《Spring Security-JWT-OAuth2一本通》
- 《实战前后端分离RBAC权限管理系统》
- 《实战SpringCloud微服务从青铜到王者》
- 《VUE深入浅出系列》
精讲RestTemplate第8篇-请求失败自动重试机制的更多相关文章
- 精讲响应式WebClient第6篇-请求失败自动重试机制,强烈建议你看一看
本文是精讲响应式WebClient第6篇,前篇的blog访问地址如下: 精讲响应式webclient第1篇-响应式非阻塞IO与基础用法 精讲响应式WebClient第2篇-GET请求阻塞与非阻塞调用方 ...
- 精讲RestTemplate第10篇-使用代理作为跳板发送请求
本文是精讲RestTemplate第10篇,前篇的blog访问地址如下: 精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用 精讲RestTemplate第2篇-多种底层 ...
- 精讲RestTemplate第9篇-如何通过HTTP Basic Auth认证
本文是精讲RestTemplate第9篇,前篇的blog访问地址如下: 精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用 精讲RestTemplate第2篇-多种底层H ...
- 精讲RestTemplate第7篇-自定义请求失败异常处理
本文是精讲RestTemplate第7篇,前篇的blog访问地址如下: 精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用 精讲RestTemplate第2篇-多种底层H ...
- 精讲RestTemplate第3篇-GET请求使用方法详解
本文是精讲RestTemplate第3篇,前篇的blog访问地址如下: 精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用 精讲RestTemplate第2篇-多种底层H ...
- 精讲RestTemplate第4篇-POST请求方法使用详解
本文是精讲RestTemplate第4篇,前篇的blog访问地址如下: 精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用 精讲RestTemplate第2篇-多种底层H ...
- 精讲RestTemplate第4篇-DELETE、PUT等请求方法使用详解
本文是精讲RestTemplate第5篇,前篇的blog访问地址如下: 精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用 精讲RestTemplate第2篇-多种底层H ...
- 精讲RestTemplate第6篇-文件上传下载与大文件流式下载
本文是精讲RestTemplate第6篇,前篇的blog访问地址如下: 精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用 精讲RestTemplate第2篇-多种底层H ...
- 精讲RestTemplate第2篇-多种底层HTTP客户端类库的切换
本文是精讲RestTemplate第2篇,前篇的blog访问地址如下: 精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用 RestTemplate只是对其他的HTTP客 ...
随机推荐
- pyinstall打包资源文件
相关代码 main.py import sys import os #生成资源文件目录访问路径 #说明: pyinstaller工具打包的可执行文件,运行时sys.frozen会被设置成True # ...
- 高效C++:继承和实现
如何正确的使用继承和实现是本章说明的重点. 确定public继承的关系是is-a public继承等同于is-a 对public继承,所有base的特性,在derived上都适用 避免遮掩继承而来的名 ...
- Windows下给PHP安装redis扩展
一.选择适合的版本 二.下载扩展 官网下载地址:http://pecl.php.net/package/redis ,选择合适的版本进行下载 三.解压后将下面两个文件复制到PHP扩展文件目录(ext文 ...
- windows 下安装YApi及集成Idea的YapiUpload
一准备工具 Mongodb Node和npm 二文档地址 https://hellosean1025.github.io/yapi/ 三安装步骤 1.安装Mongodb,请参考 2.安装Node,请参 ...
- Django开发之Ajax 返回内容报错
预期效果 Django通过Ajax POST提交数据,前台弹窗处理结果 粗略代码 # views.py 代码 ...省略... msg = { 'code': 200, 'message': 'Hel ...
- Python 爬取网易云歌手的50首热门作品
使用 requests 爬取网易云音乐 Python 代码: import json import os import time from bs4 import BeautifulSoup impor ...
- Python os.tcsetpgrp() 方法
概述 os.tcsetpgrp() 方法用于设置与终端fd(一个由os.open()返回的打开的文件描述符)关联的进程组为pg.高佣联盟 www.cgewang.com 语法 tcsetpgrp()方 ...
- PHP ftp_size() 函数
定义和用法 ftp_size() 函数返回 FTP 服务器上指定文件的大小. 该函数以字节返回指定文件的大小,如果出错则返回 -1. 语法 ftp_size(ftp_connection,file) ...
- PHP ezmlm_hash() 函数
定义和用法 ezmlm_hash() 函数用于在 MySQL 数据库中保存 EZMLM 邮件列表的哈希值. 该函数接收一个 Email 地址参数,返回一个整数哈希值. 语法 int ezmlm_has ...
- PHP sqrt() 函数
实例 返回不同数的平方根: <?phpecho(sqrt(0) . "<br>");echo(sqrt(1) . "<br>"); ...