RestTemplateTimeOutConfig.java 1.38 KB
package com.lhcredit.framework.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

/**
 * 设置RestTemplate超时时间,单位:毫秒
 * 如这里设置为10分钟
 */
@Configuration
public class RestTemplateTimeOutConfig {

    /**
     * 设置全局超时时间为2分钟(单位是毫秒)
     */
    @Bean
    public RestTemplate restTemplate() {
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(120000); // 请求连接超时时间2分钟
        httpRequestFactory.setConnectTimeout(120000); // 连接超时时间2分钟
        httpRequestFactory.setReadTimeout(120000); // 读取超时时间2分钟
        httpRequestFactory.setBufferRequestBody(false);
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().set(1,
                new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 支持中文编码
        return restTemplate;
    }
}