新西兰服务器

Springboot RestTemplate如何设置超时时间


Springboot RestTemplate如何设置超时时间

发布时间:2022-01-23 13:45:41 来源:高防服务器网 阅读:83 作者:小新 栏目:开发技术

这篇“Springboot RestTemplate如何设置超时时间”除了程序员外大部分人都不太理解,今天小编为了让大家更加理解“Springboot RestTemplate如何设置超时时间”,给大家总结了以下内容,具有一定借鉴价值,内容详细步骤清晰,细节处理妥当,希望大家通过这篇文章有所收获,下面让我们一起来看看具体内容吧。

RestTemplate未设置超时时间,导致RabbitMQ队列大量堆积,消费者假死,不进行消费,类似线程堵塞。

排查:

从日志排查问题,在从进入消费者到结束期间,会调用业务服务,然而通过开始时间至结束时间,花费的时间竟然高达100多秒,查看业务服务未发现异常。出现这种问题的原因也有可能在消费期间网络波动导致HTTP连接出现问题,一直处于等待状态。由此判断可能是HTTP超时时间未设置导致的问题。

本文生产环境Springboot版本 2.1.5.RELEASE,采用的是Java config配置

Java Config配置

@Configuration  public class RestTemplateConfig {      @Bean      public RestTemplate getRestTemplate() {          //配置HTTP超时时间          HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();          httpRequestFactory.setConnectionRequestTimeout(6000);          httpRequestFactory.setConnectTimeout(6000);          httpRequestFactory.setReadTimeout(6000);          return new RestTemplate(httpRequestFactory);      }  }

配置文件指定

custom.rest.connection.connection-request-timeout=3000  custom.rest.connection.connect-timeout=3000  custom.rest.connection.read-timeout=3000
@Configuration  public class AppConfig{      @Bean      @ConfigurationProperties(prefix = "custom.rest.connection")      public HttpComponentsClientHttpRequestFactory customHttpRequestFactory() {          return new HttpComponentsClientHttpRequestFactory();      }      @Bean      public RestTemplate customRestTemplate(){          return new RestTemplate(customHttpRequestFactory());      }  }

重新部署后消费者迅速开始消费,堆积的消息已经消费完。

RestTemplate 设置超时时间注意点

1、保证系统中只有一个RestTemplate的配置;不然可能与你的预期不一致。

2、永远不要太相信自己写的代码;多打印日志才能真正知道调用时间;

long s = System.currentTimeMillis();          try {              responseEntity = restTemplate.exchange();          } catch (Exception e) {              long costTime = System.currentTimeMillis()-s;              log.error("调用**服务异常,花费时间:{},错误:{}",costTime, e.getMessage(), e);          }

感谢您的阅读,希望您对“Springboot RestTemplate如何设置超时时间”这一关键问题有了一定的理解,具体使用情况还需要大家自己动手实验使用过才能领会,快去试试吧,如果想阅读更多相关知识点的文章,欢迎关注高防服务器网行业资讯频道!

[微信提示:高防服务器能助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。

[图文来源于网络,不代表本站立场,如有侵权,请联系高防服务器网删除]
[