首页 > 其他分享 >RestTemplate 设置超时时间(转发)

RestTemplate 设置超时时间(转发)

时间:2023-01-05 09:56:13浏览次数:53  
标签:restTemplate RestTemplate headers clientHttpRequestFactory 转发 new 超时

项目访问量大,频繁调取其他系统接口经常出现项目后台假死现象,发现其他系统掉线重启一段时间必现。查看调用接口,同事直接引用了RestTemplate但是没有设置超时时间->_<-。

两种方式:
1.添加 RestTemplateConfig

@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);
    }
}

12345678910111213
  1. 用上面和其他微服务模块有冲突,重写Bean
@Slf4j
public class LocalHttpUtil {
	public static HttpClient httpClient() {
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		try {
			//设置信任ssl访问
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (arg0, arg1) -> true).build();
			httpClientBuilder.setSSLContext(sslContext);
			HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
			SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
			Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
					// 注册http和https请求
					.register("http", PlainConnectionSocketFactory.getSocketFactory())
					.register("https", sslConnectionSocketFactory).build();

			//使用Httpclient连接池的方式配置(推荐),同时支持netty,okHttp以及其他http框架
			PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
			// 最大连接数
			poolingHttpClientConnectionManager.setMaxTotal(1000);
			// 同路由并发数
			poolingHttpClientConnectionManager.setDefaultMaxPerRoute(100);
			//配置连接池
			httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager);
			// 重试次数
			httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(0, true));
			//设置默认请求头
			List<Header> headers = new ArrayList<>();
			httpClientBuilder.setDefaultHeaders(headers);
			return httpClientBuilder.build();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static ClientHttpRequestFactory clientHttpRequestFactory(int connectTimeOut, int readTimeOut) {
		HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient());
		// 连接超时(毫秒),配置动态设置(秒)
		clientHttpRequestFactory.setConnectTimeout(connectTimeOut * 1000);
		// 数据读取超时时间(毫秒),配置动态设置(秒)
		clientHttpRequestFactory.setReadTimeout(readTimeOut * 1000);
		// 从连接池获取请求连接的超时时间(毫秒),不宜过长,必须设置,比如连接不够用时,时间过长将是灾难性的
		clientHttpRequestFactory.setConnectionRequestTimeout(connectTimeOut * 1000);
		return clientHttpRequestFactory;
	}
}



123456789101112131415161718192021222324252627282930313233343536373839404142434445464748

Service实现类中引用

public RestTemplate restTemplate(){
		//创建RestTemplate的时候,指定ClientHttpRequestFactory
		return new RestTemplate(LocalHttpUtil.clientHttpRequestFactory(mainConfigProperties.getHttpConnectTimeout(),mainConfigProperties.getHttpReadTimeout()));
	}

//调用例子	
String 	restStr = restTemplate.getForObject(url, String.class);

//调用例子 带请求头的请求
		//POST请求——参数拼接类型
		RestTemplate restTemplate = this.restTemplate(); 
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		headers.add("Authorization", Common.BASIC_AUTHORIZATION);
		String rawText = "username="+ username +"&password=" +mainConfigProperties.gePsd();
		HttpEntity<String> formEntity = new HttpEntity<String>(rawText, headers);
		ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, formEntity, String.class);


		org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
		ResponseEntity<String> responseEntity = null;
		if(Common.HTTP_METHOD.GET.equals(httpMethod)){
			//GET请求
			headers.add("Authorization", queryInfo.getAuthorization());
			HttpEntity<String> formEntity = new HttpEntity<String>( headers);
			responseEntity = restTemplate.exchange(url, HttpMethod.GET, formEntity, String.class);
		}else{
			//POST请求——参数JSON类型
			HttpEntity<String> formEntity = new HttpEntity<String>(JSON.toJSON(参数实体).toString(),headers);
			headers.setContentType(MediaType.APPLICATION_JSON);
			headers.add("Authorization", queryInfo.getAuthorization());
			responseEntity = restTemplate.exchange(url, HttpMethod.POST, formEntity, String.class);
		}

原文链接:https://blog.csdn.net/move_on_on/article/details/126544887

标签:restTemplate,RestTemplate,headers,clientHttpRequestFactory,转发,new,超时
From: https://www.cnblogs.com/zhangruifeng/p/17026687.html

相关文章

  • 二层转发原理
    一、什么是二层转发二层转发就是基于MAC地址进行数据包转发。1.二层指的就是网络七层模型中的数据链路层2.数据链路层传输的数据单元叫–帧以太帧格式前两个字......
  • linux环境通过nginx转发allure报告
    前言:  自动化测试生成的allure报告一般通过jenkins生成,生成后通过jenkins的view账号进行查看,但这样就必须登录jenkins才能看到,如何不通过登录jenkins从而看到allure报告......
  • Spring RestTemplate 专题
    相同的参数(接口的入参json打印在日志了)在PostMan中返回预期的数据,但使用RestTemplate时去提示信息错误(参数中汉字)。这种情况,搞得怀疑对RestTemplate的理解了使用RestTempla......
  • RestTemplate Module|休息模板模块
    2.1引言Spring的RestTemplate是一个健壮的、流行的基于Java的REST客户端。SpringforAndroidRestTemplateModule提供了一个在Android环境中工作的RestTempla......
  • RestTemplate、 ribbon、 OpenFeign 关系
    RestTemplateRestTemplate使用的是:spring-web包下面的http模块的http包中的API,也就是Spring自己封装的一套的httpclientAPI,下面还是走java的HttpurlConnectio......
  • Win10使用SSH反向隧道(端口转发)连接远程桌面
    应用场景:如果你有Linux云主机(腾讯、华为等),且公司有一台只有内网IP(或动态IP)的Win10工作机;你计划在家里工作时,通过家里的电脑连接公司的工作机(且不想使用类似Teamvi......
  • 理解C++ 左值右值、移动构造函数、交换操作 `swap`、移动操作 `std::move` 、转发操作
    理解C++左值右值、移动构造函数、交换操作swap、移动操作std::move、转发操作std::forward本文基于C++primer。基本上是对C++primer相关内容的一个摘录和总结。仅......
  • Qt音视频开发08-ffmpeg内核优化(极速打开/超时回调/实时响应)
    一、前言最初编写这套视频解析组件的时候,面对的场景是视频监控行业,对应设备都是网络监控摄像机,传过来的都是rtsp这种视频流,做过这一块的人都知道,打开某个视频流默认耗时比......
  • websocket 多个nginx转发
    官网http://nginx.org/en/docs/http/websocket.html第一个nginxserver{listen6794;root/mnt/dist;location/analyze/{prox......
  • node.js编写反向代理转发https
    node.js编写反向代理转发httpsconstcrypto=require("crypto");constmd5=function(str){constmd5=crypto.createHash('md5');md5.update(str);......