application.properties:

 #代理设置
proxy.enabled=false
proxy.host=192.168.18.233
proxy.port=8888 #REST超时配置
rest.ReadTimeout=35000
rest.ConnectTimeout=5000

代理配置类:

 import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; import lombok.Data; /**
* 网络代理设置
*
* @author yangzhilong
*
*/
@Component
@ConfigurationProperties(prefix="proxy")
@Data
public class ProxyConfig {
/**
* 是否启用代理
*/
private Boolean enabled;
/**
* 代理主机地址
*/
private String host;
/**
* 代理端口
*/
private Integer port;
}

SpringBoot的Configuration:

 import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate; import com.yzl.vo.ProxyConfig; @Configuration
@ConditionalOnClass(ProxyConfig.class)
public class RestConfiguration {
@Value("${rest.ReadTimeout}")
private int readTimeout;
@Value("${rest.ConnectTimeout}")
private int connectionTimeout;
@Autowired
private ProxyConfig proxyConfig; @Bean
public SimpleClientHttpRequestFactory httpClientFactory() {
SimpleClientHttpRequestFactory httpRequestFactory = new SimpleClientHttpRequestFactory();
httpRequestFactory.setReadTimeout(readTimeout);
httpRequestFactory.setConnectTimeout(connectionTimeout); if(proxyConfig.getEnabled()){
SocketAddress address = new InetSocketAddress(proxyConfig.getHost(), proxyConfig.getPort());
Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
httpRequestFactory.setProxy(proxy);
} return httpRequestFactory;
} @Bean
public RestTemplate restTemplate(SimpleClientHttpRequestFactory httpClientFactory) {
RestTemplate restTemplate = new RestTemplate(httpClientFactory);
return restTemplate;
}
}

如果不希望这种全局的超时时间污染正常的SpringCloud中restTemplate的时间设置,可以使用如下方法:

 package com.yzl.autoconfig;

 import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate; import com.yzl.util.RestClient; /**
* 工具类引导装配类
* @author yangzhilong
*
*/
@Configuration
public class RestClientAutoConfiguration {
@Value("${rest.config.connectTimeout:10000}")
private int connectTimeout;
@Value("${rest.config.readTimeout:30000}")
private int readTimeout; /**
* 使用Bootstrap来装配RestClient中的RestTemplate属性,
* 避免直接装配RestTemplate来污染了正常的spring Cloud的调用
* @return
*/
@Bean
public RestClientBootstrap bootstrap(){
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
httpRequestFactory.setConnectTimeout(connectTimeout);
httpRequestFactory.setReadTimeout(readTimeout);
RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
RestClient.setRestTemplate(restTemplate);
return new RestClientBootstrap();
} /**
* 空的引导类
* @author yangzhilong
*
*/
static class RestClientBootstrap { }
}

RestClient工具类:

package com.nike.gcsc.auth.utils;

import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate; import com.alibaba.fastjson.JSON; /**
* HTTP Rest Util
* @author yangzhilong
*
*/
public class RestClient { private static RestTemplate restTemplate; /**
* @param client
*/
public static void setRestTemplate(RestTemplate client) {
restTemplate = client;
} /**
*
* @param <T>
* @param url
* @param clasz
* @return
*/
public static <T> T get(String url, Class<T> clasz) {
return restTemplate.getForObject(url , clasz);
} /**
*
* @param <T>
* @param url
* @param headMap
* @param bodyObj
* @param clasz
* @return
*/
public static <T> T postJson(String url, Map<String, String> headMap, Object bodyObj, Class<T> clasz) {
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(type);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
if(null != headMap) {
headMap.entrySet().forEach(item -> {
headers.add(item.getKey(), item.getValue());
});
}
String result = null;
if(bodyObj == null){
result = "{}";
}else{
result = JSON.toJSONString(bodyObj);
}
HttpEntity<String> formEntity = new HttpEntity<String>(result,headers);
return restTemplate.postForObject(url , formEntity, clasz);
} /**
*
* @param <T>
* @param url
* @param attrMap
* @param clasz
* @return
*/
public static <T> T postForm(String url, Map<String , String> attrMap, Class<T> clasz){
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> params= new LinkedMultiValueMap<>();
attrMap.entrySet().forEach(item -> {
params.add(item.getKey() , item.getValue()); });
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
return restTemplate.exchange(url, HttpMethod.POST, requestEntity, clasz).getBody();
} }

然后实际发起HTTP请求的时候使用上面的工具类

SpringBoot配置RestTemplate的代理和超时时间的更多相关文章

  1. SpringBoot修改默认端口号,session超时时间

    有时候我们可能需要启动不止一个SpringBoot,而SpringBoot默认的端口号是8080,所以这时候我们就需要修改SpringBoot的默认端口了.修改SpringBoot的默认端口有两种方式 ...

  2. 【Spring Cloud 源码解读】之 【如何配置好OpenFeign的各种超时时间!】

    关于Feign的超时详解: 在Spring Cloud微服务架构中,大部分公司都是利用Open Feign进行服务间的调用,而比较简单的业务使用默认配置是不会有多大问题的,但是如果是业务比较复杂,服务 ...

  3. hystrix ,feign,ribbon的超时时间配置,以及原理分析

    背景,网上看到很多关于hystrix的配置都是没生效的,如: 一.先看测试环境搭建: order 服务通过feign 的方式调用了product 服务的getProductInfo 接口 //---- ...

  4. nginx限制上传大小和超时时间设置说明/php限制上传大小

    现象说明:在服务器上部署了一套后台环境,使用的是nginx反向代理tomcat架构,在后台里上传一个70M的视频文件,上传到一半就失效了! 原因是nginx配置里限制了上传文件的大小 client_m ...

  5. (转)nginx限制上传大小和超时时间设置说明/php限制上传大小

    nginx限制上传大小和超时时间设置说明/php限制上传大小 原文:http://www.cnblogs.com/kevingrace/p/6093671.html 现象说明:在服务器上部署了一套后台 ...

  6. Nginx上传和超时时间限制 (php上传限制) - 运维笔记

    现象说明:在服务器上部署了一套后台环境,使用的是nginx反向代理tomcat架构,在后台里上传一个70M的视频文件,上传到一半就失效了! 原因:nginx配置里限制了上传文件的大小 client_m ...

  7. scrapy 如何使用代理 以及设置超时时间

    使用代理 1. 单文件spider局部使用代理 entry = 'http://xxxxx:xxxxx@http-pro.abuyun.com:xxx'.format("帐号", ...

  8. config文件中可以配置查询超时时间

    web.config配置数据库连接 第一种:获取连接字符串 首先要定义命名空间 system.configuration 1.  string connstr= string constr = Con ...

  9. GRUB2配置详解:默认启动项,超时时间,隐藏引导菜单,配置文件详解,图形化配置

    配置文件详解: /etc/default/grub # 设定默认启动项,推荐使用数字 GRUB_DEFAULT=0 # 注释掉下面这行将会显示引导菜单 #GRUB_HIDDEN_TIMEOUT=0 # ...

随机推荐

  1. Invalid Host header 的解决方案

    composer 显示:Invalid Host header的解决方案 I have tried this workaround: Edit the following line in node_m ...

  2. [转]Memcache的原理和命中率的总结

    From : http://blog.csdn.net/hbzyaxiu520/article/details/19546969 1       Memcache是什么Memcache是danga.c ...

  3. [转载][HASS.IO] 【HASSOS安装】成功安装HASSOS 1.9(避开了大部分坑版)

    7月20日HA官方放出HASSOS说明时,我开始入坑HASSOS,经历了安装没流量.打开主页:8123没显示.HASS.IO边栏不显示.安装不了HASS.IO插件等问题之后,在8月6日总算避开了大坑进 ...

  4. 第一章 Java加解密简介

    1.加密算法: 移位.替代(古典加密) 对称加密:DES.AES 非对称加密:RSA 散列函数算法(单向加密):MD5.SHA.Mac 数字签名算法:RSA.DSA 其中,前三种主要完成数据的加解密: ...

  5. window.open 浏览器差异.

    首先引入 w3help的,莫的测试: 原帖地址:http://www.w3help.org/zh-cn/causes/BX1053   w3help的测试,和我的测试相互补充,应该比较完整了.悲剧的是 ...

  6. 网络监测 断网 网速 ping 完整案例 MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  7. MFC中如何给静态文本框添加消息响应

    需要两个步骤: 第一个: 是改变它的ID(默认情况下所有的静态文本框的ID都为IDC_STATIC,你需要改变他的ID为其他的值). 第二个: 是在它的属性对话框中选中Notify选项,VS是将该属性 ...

  8. linux命令学习——cat

    1.前言 今天需要处理一个oui.txt文件,需要从中抽丝man和orginaziton信息,导出到另外一个文件中.可以cat和grep命令进行操作.之前对cat命令了解一下,知道cat可以查看文件内 ...

  9. HTML常见元素及其属性总结

    HTML视频看完了.视频非常短,主要讲述了有关HTML中经常使用的标记和元素属性的使用.这对理解web开发有非常大的帮助.之前做过的牛腩新闻公布系统中用到了非常短HTML元素,仅仅是跟着视频做,非常多 ...

  10. MySQL表级锁和行级锁

    一:概述 相对其他数据库而言,MySQL的锁机制比较简单,其最显著的特点是不同的存储引擎支持不同的锁机制.比如,MyISAM和MEMORY存储引擎采用的是表级锁(table-level locking ...