SpringBoot 配置 okhttp3的操作
1.Maven添加依赖
com.squareup.okhttp3 okhttp 3.10.0
2.application.properties配置文件
ok.http.connect-timeout=30 ok.http.read-timeout=30 ok.http.write-timeout=30 #连接池中整体的空闲连接的最大数量 ok.http.max-idle-connections=200 #连接空闲时间最多为300秒 ok.http.keep-alive-duration=300
3.OkHttpConfiguration配置类
importokhttp3.ConnectionPool;
importokhttp3.OkHttpClient;
importorg.springframework.beans.factory.annotation.Value;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
importjavax.net.ssl.*;
importjava.security.*;
importjava.security.cert.CertificateException;
importjava.security.cert.X509Certificate;
importjava.util.concurrent.TimeUnit;
/**
*@authorAnswer.AI.L
*@date2019-04-09
*/
@Configuration
publicclassOkHttpConfiguration{
@Value("${ok.http.connect-timeout}")
privateIntegerconnectTimeout;
@Value("${ok.http.read-timeout}")
privateIntegerreadTimeout;
@Value("${ok.http.write-timeout}")
privateIntegerwriteTimeout;
@Value("${ok.http.max-idle-connections}")
privateIntegermaxIdleConnections;
@Value("${ok.http.keep-alive-duration}")
privateLongkeepAliveDuration;
@Bean
publicOkHttpClientokHttpClient(){
returnnewOkHttpClient.Builder()
.sslSocketFactory(sslSocketFactory(),x509TrustManager())
//是否开启缓存
.retryOnConnectionFailure(false)
.connectionPool(pool())
.connectTimeout(connectTimeout,TimeUnit.SECONDS)
.readTimeout(readTimeout,TimeUnit.SECONDS)
.writeTimeout(writeTimeout,TimeUnit.SECONDS)
.hostnameVerifier((hostname,session)->true)
//设置代理
// .proxy(newProxy(Proxy.Type.HTTP,newInetSocketAddress("127.0.0.1",8888)))
//拦截器
//.addInterceptor()
.build();
}
@Bean
publicX509TrustManagerx509TrustManager(){
returnnewX509TrustManager(){
@Override
publicvoidcheckClientTrusted(X509Certificate[]chain,StringauthType)
throwsCertificateException{
}
@Override
publicvoidcheckServerTrusted(X509Certificate[]chain,StringauthType)
throwsCertificateException{
}
@Override
publicX509Certificate[]getAcceptedIssuers(){
returnnewX509Certificate[0];
}
};
}
@Bean
publicSSLSocketFactorysslSocketFactory(){
try{
//信任任何链接
SSLContextsslContext=SSLContext.getInstance("TLS");
sslContext.init(null,newTrustManager[]{x509TrustManager()},newSecureRandom());
returnsslContext.getSocketFactory();
}catch(NoSuchAlgorithmException|KeyManagementExceptione){
e.printStackTrace();
}
returnnull;
}
@Bean
publicConnectionPoolpool(){
returnnewConnectionPool(maxIdleConnections,keepAliveDuration,TimeUnit.SECONDS);
}
}
4.OkHttp类
importlombok.extern.slf4j.Slf4j;
importokhttp3.*;
importorg.apache.commons.lang3.exception.ExceptionUtils;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.stereotype.Component;
importjava.util.Map;
/**
*@authorAnswer.AI.L
*@date2019-04-09
*/
@Slf4j
@Component
publicclassOkHttpCli{
privatestaticfinalMediaTypeJSON=MediaType.parse("application/json;charset=utf-8");
privatestaticfinalMediaTypeXML=MediaType.parse("application/xml;charset=utf-8");
@Autowired
privateOkHttpClientokHttpClient;
/**
*get请求
*@paramurl请求url地址
*@returnstring
**/
publicStringdoGet(Stringurl){
returndoGet(url,null,null);
}
/**
*get请求
*@paramurl请求url地址
*@paramparams请求参数map
*@returnstring
**/
publicStringdoGet(Stringurl,Mapparams){
returndoGet(url,params,null);
}
/**
*get请求
*@paramurl请求url地址
*@paramheaders请求头字段{k1,v1k2,v2,...}
*@returnstring
**/
publicStringdoGet(Stringurl,String[]headers){
returndoGet(url,null,headers);
}
/**
*get请求
*@paramurl请求url地址
*@paramparams请求参数map
*@paramheaders请求头字段{k1,v1k2,v2,...}
*@returnstring
**/
publicStringdoGet(Stringurl,Mapparams,String[]headers){
StringBuildersb=newStringBuilder(url);
if(params!=null&¶ms.keySet().size()>0){
booleanfirstFlag=true;
for(Stringkey:params.keySet()){
if(firstFlag){
sb.append("?").append(key).append("=").append(params.get(key));
firstFlag=false;
}else{
sb.append("&").append(key).append("=").append(params.get(key));
}
}
}
Request.Builderbuilder=newRequest.Builder();
if(headers!=null&&headers.length>0){
if(headers.length%2==0){
for(inti=0;iparams){
FormBody.Builderbuilder=newFormBody.Builder();
if(params!=null&¶ms.keySet().size()>0){
for(Stringkey:params.keySet()){
builder.add(key,params.get(key));
}
}
Requestrequest=newRequest.Builder().url(url).post(builder.build()).build();
log.info("dopostrequestandurl[{}]",url);
returnexecute(request);
}
/**
*post请求,请求数据为json的字符串
*@paramurl请求url地址
*@paramjson请求数据,json字符串
*@returnstring
*/
publicStringdoPostJson(Stringurl,Stringjson){
log.info("dopostrequestandurl[{}]",url);
returnexectePost(url,json,JSON);
}
/**
*post请求,请求数据为xml的字符串
*@paramurl请求url地址
*@paramxml请求数据,xml字符串
*@returnstring
*/
publicStringdoPostXml(Stringurl,Stringxml){
log.info("dopostrequestandurl[{}]",url);
returnexectePost(url,xml,XML);
}
privateStringexectePost(Stringurl,Stringdata,MediaTypecontentType){
RequestBodyrequestBody=RequestBody.create(contentType,data);
Requestrequest=newRequest.Builder().url(url).post(requestBody).build();
returnexecute(request);
}
privateStringexecute(Requestrequest){
Responseresponse=null;
try{
response=okHttpClient.newCall(request).execute();
if(response.isSuccessful()){
returnresponse.body().string();
}
}catch(Exceptione){
log.error(ExceptionUtils.getStackTrace(e));
}finally{
if(response!=null){
response.close();
}
}
return"";
}
}
5.使用验证
@RestController
publicclassAnswerController{
@Autowired
privateOkHttpCliokHttpCli;
@RequestMapping(value="show",method=RequestMethod.GET)
publicStringshow(){
Stringurl="https://www.baidu.com/";
Stringmessage=okHttpCli.doGet(url);
returnmessage;
}
}
6.双向认证(待证)
@Bean
publicSSLSocketFactorysslSocketFactory(){
StringcertPath="";
StringcaPath="";
StringcertPwd="";
StringcaPwd="";
try{
ClassPathResourceselfcertPath=newClassPathResource(certPath);
ClassPathResourcetrustcaPath=newClassPathResource(caPath);
KeyStoreselfCert=KeyStore.getInstance("pkcs12");
selfCert.load(selfcertPath.getInputStream(),certPwd.toCharArray());
KeyManagerFactorykmf=KeyManagerFactory.getInstance("sunx509");
kmf.init(selfCert,certPwd.toCharArray());
KeyStorecaCert=KeyStore.getInstance("jks");
caCert.load(trustcaPath.getInputStream(),caPwd.toCharArray());
TrustManagerFactorytmf=TrustManagerFactory.getInstance("sunx509");
tmf.init(caCert);
SSLContextsslContext=SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(),tmf.getTrustManagers(),null);
returnsslContext.getSocketFactory();
}catch(Exceptione){
e.printStackTrace();
}
returnnull;
}
补充:SpringCloudFeign总结问题,注意点,性能调优,切换okhttp3
Feign常见问题总结
FeignClient接口如使用@PathVariable,必须指定value属性
//在一些早期版本中,@PathVariable("id")中的"id",也就是value属性,必须指定,不能省略。
@FeignClient("microservice-provider-user")
publicinterfaceUserFeignClient{
@RequestMapping(value="/simple/{id}",method=RequestMethod.GET)
publicUserfindById(@PathVariable("id")Longid);
...
}
Java代码自定义FeignClient的注意点与坑
@FeignClient(name="microservice-provider-user",configuration=UserFeignConfig.class)
publicinterfaceUserFeignClient{
@GetMapping("/users/{id}")
UserfindById(@PathVariable("id")Longid);
}
/**
*该FeignClient的配置类,注意:
*1.该类可以独立出去;
*2.该类上也可添加@Configuration声明是一个配置类;
*配置类上也可添加@Configuration注解,声明这是一个配置类;
*但此时千万别将该放置在主应用程序上下文@ComponentScan所扫描的包中,
*否则,该配置将会被所有FeignClient共享,无法实现细粒度配置!
*个人建议:像我一样,不加@Configuration注解
*
*@authorzhouli
*/
classUserFeignConfig{
@Bean
publicLogger.Levellogger(){
returnLogger.Level.FULL;
}
}
配置类上也可添加@Configuraiton注解,声明这是一个配置类;但此时千万别将该放置在主应用程序上下文@ComponentScan所扫描的包中,否则,该配置将会被所有FeignClient共享(相当于变成了通用配置,其实本质还是Spring父子上下文扫描包重叠导致的问题),无法实现细粒度配置!
个人建议:像我一样,不加@Configuration注解,省得进坑。
最佳实践:尽量用配置属性自定义Feign的配置!!!
@FeignClient注解属性
//@FeignClient(name="microservice-provider-user")
//在早期的SpringCloud版本中,无需提供name属性,从Brixton版开始,@FeignClient必须提供name属性,否则应用将无法正常启动!
//另外,name、url等属性支持占位符。例如:
@FeignClient(name="${feign.name}",url="${feign.url}")
类级别的@RequestMapping会被SpringMVC加载
@RequestMapping("/users")
@FeignClient(name="microservice-user")
publicclassTestFeignClient{
//...
}
类上的@RequestMapping注解也会被SpringMVC加载。该问题现已经被解决,早期的版本有两种解决方案:方案1:不在类上加@RequestMapping注解;方案2:添加如下代码:
@Configuration
@ConditionalOnClass({Feign.class})
publicclassFeignMappingDefaultConfiguration{
@Bean
publicWebMvcRegistrationsfeignWebRegistrations(){
returnnewWebMvcRegistrationsAdapter(){
@Override
publicRequestMappingHandlerMappinggetRequestMappingHandlerMapping(){
returnnewFeignFilterRequestMappingHandlerMapping();
}
};
}
privatestaticclassFeignFilterRequestMappingHandlerMappingextendsRequestMappingHandlerMapping{
@Override
protectedbooleanisHandler(Class>beanType){
returnsuper.isHandler(beanType)&&!beanType.isInterface();
}
}
}
首次请求失败Ribbon的饥饿加载(eager-load)模式
如需产生HystrixStream监控信息,需要做一些额外操作Feign本身已经整合了Hystrix,可直接使用@FeignClient(value="microservice-provider-user",fallback=XXX.class)来指定fallback类,fallback类继承@FeignClient所标注的接口即可。
但是假设如需使用HystrixStream进行监控,默认情况下,访问http://IP:PORT/actuator/hystrix.stream是会返回404,这是因为Feign虽然整合了Hystrix,但并没有整合Hystrix的监控。如何添加监控支持呢?需要以下几步:
第一步:添加依赖,示例:
org.springframework.cloud spring-cloud-starter-hystrix
第二步:在启动类上添加@EnableCircuitBreaker注解,示例:
@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient
@EnableCircuitBreaker
publicclassMovieFeignHystrixApplication{
publicstaticvoidmain(String[]args){
SpringApplication.run(MovieFeignHystrixApplication.class,args);
}
}
第三步:在application.yml中添加如下内容,暴露hystrix.stream端点:
management: endpoints: web: exposure: include:'hystrix.stream'
这样,访问任意FeignClient接口的API后,再访问http://IP:PORT/actuator/hystrix.stream,就会展示一大堆Hystrix监控数据了。
Feign上传文件
加依赖
io.github.openfeign.form feign-form 3.0.3 io.github.openfeign.form feign-form-spring 3.0.3
编写FeignClient
@FeignClient(name="ms-content-sample",configuration=UploadFeignClient.MultipartSupportConfig.class)
publicinterfaceUploadFeignClient{
@RequestMapping(value="/upload",method=RequestMethod.POST,
produces={MediaType.APPLICATION_JSON_UTF8_VALUE},
consumes=MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseBody
StringhandleFileUpload(@RequestPart(value="file")MultipartFilefile);
classMultipartSupportConfig{
@Bean
publicEncoderfeignFormEncoder(){
returnnewSpringFormEncoder();
}
}
}
如代码所示,在这个FeignClient中,我们引用了配置类MultipartSupportConfig,在MultipartSupportConfig中,我们实例化了SpringFormEncoder。这样这个FeignClient就能够上传啦。
注意点
//RequestMapping注解中的produeces、consumes不能少;
@RequestMapping(value="/upload",method=RequestMethod.POST,
produces={MediaType.APPLICATION_JSON_UTF8_VALUE},
consumes=MediaType.MULTIPART_FORM_DATA_VALUE)
接口定义中的注解@RequestPart(value="file")不能写成@RequestParam(value="file")。
最好将Hystrix的超时时间设长一点,例如5秒,否则可能文件还没上传完,Hystrix就超时了,从而导致客户端侧的报错。
Feign实现Form表单提交
添加依赖:
io.github.openfeign.form feign-form 3.2.2 io.github.openfeign.form feign-form-spring 3.2.2
FeignClient示例:
@FeignClient(name="xxx",url="http://www.itmuch.com/",configuration=TestFeignClient.FormSupportConfig.class)
publicinterfaceTestFeignClient{
@PostMapping(value="/test",
consumes={MediaType.APPLICATION_FORM_URLENCODED_VALUE},
produces={MediaType.APPLICATION_JSON_UTF8_VALUE}
)
voidpost(MapqueryParam);
classFormSupportConfig{
@Autowired
privateObjectFactorymessageConverters;
//new一个form编码器,实现支持form表单提交
@Bean
publicEncoderfeignFormEncoder(){
returnnewSpringFormEncoder(newSpringEncoder(messageConverters));
}
//开启Feign的日志
@Bean
publicLogger.Levellogger(){
returnLogger.Level.FULL;
}
}
}
调用示例:
@GetMapping("/user/{id}")
publicUserfindById(@PathVariableLongid){
HashMapparam=Maps.newHashMap();
param.put("username","zhangsan");
param.put("password","pwd");
this.testFeignClient.post(param);
returnnewUser();
}
日志:
...[TestFeignClient#post]--->POSThttp://www.baidu.com/testHTTP/1.1 ...[TestFeignClient#post]Accept:application/json;charset=UTF-8 ...[TestFeignClient#post]Content-Type:application/x-www-form-urlencoded;charset=UTF-8 ...[TestFeignClient#post]Content-Length:30 ...[TestFeignClient#post] ...[TestFeignClient#post]password=pwd&username=zhangsan ...[TestFeignClient#post]--->ENDHTTP(30-bytebody)
由日志可知,此时Feign已能使用Form表单方式提交数据。
FeignGET请求如何构造多参数
假设需请求的URL包含多个参数,例如http://microservice-provider-user/get?id=1&username=张三,该如何使用Feign构造呢?我们知道,SpringCloud为Feign添加了SpringMVC的注解支持,那么我们不妨按照SpringMVC的写法尝试一下:
@FeignClient("microservice-provider-user")
publicinterfaceUserFeignClient{
@RequestMapping(value="/get",method=RequestMethod.GET)
publicUserget0(Useruser);
}
然而,这种写法并不正确,控制台会输出类似如下的异常。
feign.FeignException:status405readingUserFeignClient#get0(User);content:
{"timestamp":1482676142940,"status":405,"error":"MethodNotAllowed","exception":"org.springframework.web.HttpRequestMethodNotSupportedException","message":"Requestmethod'POST'notsupported","path":"/get"}
由异常可知,尽管我们指定了GET方法,Feign依然会使用POST方法发送请求。于是导致了异常。正确写法如下
方法一[推荐]注意:使用该方法无法使用Fegin的继承模式
@FeignClient("microservice-provider-user")
publicinterfaceUserFeignClient{
@GetMapping("/get")
publicUserget0(@SpringQueryMapUseruser);
}
方法二[推荐]
@FeignClient(name="microservice-provider-user")
publicinterfaceUserFeignClient{
@RequestMapping(value="/get",method=RequestMethod.GET)
publicUserget1(@RequestParam("id")Longid,@RequestParam("username")Stringusername);
}
这是最为直观的方式,URL有几个参数,Feign接口中的方法就有几个参数。使用@RequestParam注解指定请求的参数是什么。
方法三[不推荐]多参数的URL也可使用Map来构建。当目标URL参数非常多的时候,可使用这种方式简化Feign接口的编写。
@FeignClient(name="microservice-provider-user")
publicinterfaceUserFeignClient{
@RequestMapping(value="/get",method=RequestMethod.GET)
publicUserget2(@RequestParamMapmap);
}
在调用时,可使用类似以下的代码。
publicUserget(Stringusername,Stringpassword){
HashMapmap=Maps.newHashMap();
map.put("id","1");
map.put("username","张三");
returnthis.userFeignClient.get2(map);
}
注意:这种方式不建议使用。主要是因为可读性不好,而且如果参数为空的时候会有一些问题,例如map.put("username",null);会导致服务调用方(消费者服务)接收到的username是"",而不是null。
切换为Okhttp3提升QPS性能优化
加依赖引入okhttp3
io.github.openfeign feign-okhttp ${version}
写配置
feign: #feign启用hystrix,才能熔断、降级 #hystrix: #enabled:true #启用okhttp关闭默认httpclient httpclient: enabled:false#关闭httpclient #配置连接池 max-connections:200#feign的最大连接数 max-connections-per-route:50#fegin单个路径的最大连接数 okhttp: enabled:true #请求与响应的压缩以提高通信效率 compression: request: enabled:true min-request-size:2048 mime-types:text/xml,application/xml,application/json response: enabled:true
参数配置
/**
*配置okhttp与连接池
*ConnectionPool默认创建5个线程,保持5分钟长连接
*/
@Configuration
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)//SpringBoot自动配置
publicclassOkHttpConfig{
//默认老外留给你彩蛋中文乱码,加上它就OK
@Bean
publicEncoderencoder(){
returnnewFormEncoder();
}
@Bean
publicokhttp3.OkHttpClientokHttpClient(){
returnnewokhttp3.OkHttpClient.Builder()
//设置连接超时
.connectTimeout(10,TimeUnit.SECONDS)
//设置读超时
.readTimeout(10,TimeUnit.SECONDS)
//设置写超时
.writeTimeout(10,TimeUnit.SECONDS)
//是否自动重连
.retryOnConnectionFailure(true)
.connectionPool(newConnectionPool(10,5L,TimeUnit.MINUTES))
.build();
}
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持毛票票。如有错误或未考虑完全的地方,望不吝赐教。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。