一般来讲我们访问外部资源时,需要做一个保护,比如最常见的添加一个超时设置,避免一直被阻塞,RestTemplate可以通过 SimpleClientHttpRequestFactory
来处理超时设置
博文测试项目完全基于 【WEB系列】RestTemplate基础用法小结 的项目环境,建议配合查看
基本环境: IDEA
+ maven
+ SpringBoot 2.2.1.RELEASE
添加一个超时模拟的端点如下
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); }
主要是通过设置 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()); } }
输出如下:
(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
尽信书则不如,以上内容,纯属一家之言,因个人能力有限,难免有疏漏和错误之处,如发现bug或者有更好的建议,欢迎批评指正,不吝感激
下面一灰灰的个人博客,记录所有学习和工作中的博文,欢迎大家前去逛逛
打赏 如果觉得我的文章对您有帮助,请随意打赏。