一灰灰blog 一灰灰blog
首页
  • InfluxDB
  • MongoDB
  • MySql
  • 基础系列
  • DB系列
  • 搜索系列
  • MQ系列
  • WEB系列
  • 中间件
  • 运维
  • SpringSecurity
  • SpringCloud
  • QuickAlarm
  • QuickCrawer
  • QuickFix
  • QuickMedia
  • QuickSpi
  • QuickTask
  • 高可用
  • 分类
  • 标签
  • 归档
  • 收藏
  • 关于
GitHub (opens new window)

一灰灰blog

资深搬运工
首页
  • InfluxDB
  • MongoDB
  • MySql
  • 基础系列
  • DB系列
  • 搜索系列
  • MQ系列
  • WEB系列
  • 中间件
  • 运维
  • SpringSecurity
  • SpringCloud
  • QuickAlarm
  • QuickCrawer
  • QuickFix
  • QuickMedia
  • QuickSpi
  • QuickTask
  • 高可用
  • 分类
  • 标签
  • 归档
  • 收藏
  • 关于
GitHub (opens new window)
  • 基础系列

  • DB系列

  • 搜索系列

  • MQ系列

  • WEB系列

    • Request

    • Response

    • RestTemplate

      • 【WEB系列】RestTemplate基础用法小结
      • 【WEB系列】RestTemplate之自定义请求头
      • 【WEB系列】RestTemplate之中文乱码问题fix
      • 【WEB系列】RestTemplate之超时设置
        • I. RestTemplate超时设置
          • 1. 超时端点
          • 2. 超时设置
        • II. 其他
          • 1. 源码&系列博文
          • 1. 一灰灰Blog
      • 【WEB系列】RestTemplate之代理访问
      • 【WEB系列】RestTemplate之Basic Auth授权
      • 【WEB系列】RestTemplate之非200状态码信息捕获
      • 【WEB系列】AsyncRestTemplate之异步非阻塞网络请求介绍篇
      • 【WEB系列】RestTemplate之文件上传
      • 【WEB系列】RestTemplate之连接池配置
    • WebClient

    • WebFlux

    • WebSocket

    • Web三剑客

    • 实例

    • 其他

  • 中间件

  • 运维

  • SpringSecurity

  • SpringCloud

  • Spring系列
  • WEB系列
  • RestTemplate
一灰灰
2020-07-02

【WEB系列】RestTemplate之超时设置

一般来讲我们访问外部资源时,需要做一个保护,比如最常见的添加一个超时设置,避免一直被阻塞,RestTemplate可以通过SimpleClientHttpRequestFactory来处理超时设置

# I. RestTemplate超时设置

博文测试项目完全基于【WEB系列】RestTemplate基础用法小结 (opens new window)的项目环境,建议配合查看

基本环境:IDEA + maven + SpringBoot 2.2.1.RELEASE

# 1. 超时端点

添加一个超时模拟的端点如下

private String getHeaders(HttpServletRequest request) {
    Enumeration<String> headerNames = request.getHeaderNames();
    String name;

    JSONObject headers = new JSONObject();
    while (headerNames.hasMoreElements()) {
        name = headerNames.nextElement();
        headers.put(name, request.getHeader(name));
    }
    return headers.toJSONString();
}

private String getParams(HttpServletRequest request) {
    return JSONObject.toJSONString(request.getParameterMap());
}

private String getCookies(HttpServletRequest request) {
    Cookie[] cookies = request.getCookies();
    if (cookies == null || cookies.length == 0) {
        return "";
    }

    JSONObject ck = new JSONObject();
    for (Cookie cookie : cookies) {
        ck.put(cookie.getName(), cookie.getValue());
    }
    return ck.toJSONString();
}

private String buildResult(HttpServletRequest request) {
    return buildResult(request, null);
}

private String buildResult(HttpServletRequest request, Object obj) {
    String params = getParams(request);
    String headers = getHeaders(request);
    String cookies = getCookies(request);

    if (obj != null) {
        params += " | " + obj;
    }

    return "params: " + params + "\nheaders: " + headers + "\ncookies: " + cookies;
}

@GetMapping(path = "timeout")
public String timeOut(HttpServletRequest request) throws InterruptedException {
    Thread.sleep(60_000L);
    return buildResult(request);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

# 2. 超时设置

主要是通过设置SimpleClientHttpRequestFactory来设置超时

/**
 * 设置超时时间
 */
public void timeOut() {
    RestTemplate restTemplate = new RestTemplate();

    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    requestFactory.setConnectTimeout(1000);
    requestFactory.setReadTimeout(1000);
    restTemplate.setRequestFactory(requestFactory);
    long start = System.currentTimeMillis();
    try {
        log.info("timeOut start: {}", start);
        HttpEntity<String> response =
                restTemplate.getForEntity("http://127.0.0.1:8080/timeout?name=一灰灰&age=20", String.class);
        log.info("timeOut cost:{} response: {}", System.currentTimeMillis() - start, response);
    } catch (Exception e) {
        log.info("timeOut cost:{} exception: {}", System.currentTimeMillis() - start, e.getMessage());
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

输出如下:

(timeOut start: 1593420406204

(timeOut cost:1014 exception: I/O error on GET request for "http://127.0.0.1:8080/timeout": Read timed out; nested exception is java.net.SocketTimeoutException: Read timed out
1
2
3

# II. 其他

# 1. 源码&系列博文

博文

  • 【WEB系列】RestTemplate之中文乱码问题fix (opens new window)
  • 【WEB系列】RestTemplate之自定义请求头 (opens new window)
  • 【WEB系列】RestTemplate基础用法小结 (opens new window)

源码

  • 工程:https://github.com/liuyueyi/spring-boot-demo (opens new window)
  • 源码: https://github.com/liuyueyi/spring-boot-demo/tree/master/spring-boot/221-web-resttemplate (opens new window)

# 1. 一灰灰Blog

尽信书则不如,以上内容,纯属一家之言,因个人能力有限,难免有疏漏和错误之处,如发现bug或者有更好的建议,欢迎批评指正,不吝感激

下面一灰灰的个人博客,记录所有学习和工作中的博文,欢迎大家前去逛逛

  • 一灰灰Blog个人博客 https://blog.hhui.top (opens new window)
  • 一灰灰Blog-Spring专题博客 http://spring.hhui.top (opens new window)

一灰灰blog

编辑 (opens new window)
#RestTemplate
上次更新: 2021/10/15, 19:56:22
【WEB系列】RestTemplate之中文乱码问题fix
【WEB系列】RestTemplate之代理访问

← 【WEB系列】RestTemplate之中文乱码问题fix 【WEB系列】RestTemplate之代理访问→

最近更新
01
【基础系列】基于maven多环境配置
04-25
02
【WEB系列】内嵌Tomcat配置Accesslog日志文件生成位置源码探索
04-24
03
【搜索系列】ES查询常用实例演示
04-18
更多文章>
Theme by Vdoing | Copyright © 2017-2022 一灰灰Blog
MIT License | 鄂ICP备18017282号 |
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式
×