千家信息网

Springboot RestTemplate如何设置超时时间

发表于:2024-10-18 作者:千家信息网编辑
千家信息网最后更新 2024年10月18日,这篇"Springboot RestTemplate如何设置超时时间"除了程序员外大部分人都不太理解,今天小编为了让大家更加理解"Springboot RestTemplate如何设置超时时间",给大
千家信息网最后更新 2024年10月18日Springboot RestTemplate如何设置超时时间

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

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

排查:

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

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

Java Config配置

@Configurationpublic 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=3000custom.rest.connection.connect-timeout=3000custom.rest.connection.read-timeout=3000
@Configurationpublic 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如何设置超时时间"这一关键问题有了一定的理解,具体使用情况还需要大家自己动手实验使用过才能领会,快去试试吧,如果想阅读更多相关知识点的文章,欢迎关注行业资讯频道!

0