服务器之家

服务器之家 > 正文

基于Feign使用okhttp的填坑之旅

时间:2021-08-13 13:41     来源/作者:石楠烟斗的雾

1、由于项目需要远程调用http请求

因此就想到了Feign,因为真的非常的方便,只需要定义一个接口就行。

但是feign默认使用的JDK的URLHttpConnection,没有连接池效率不好,从Feign的自动配置类FeignAutoConfiguration中可以看到Feign除了默认的http客户端还支持okhttp和ApacheHttpClient,我这里选择了okhttp,它是有连接池的。

2、看看网络上大部分博客中是怎么使用okhttp的

1)、引入feign和okhttp的maven坐标

  1. <dependencyManagement>
  2. <dependencies>
  3. <dependency>
  4. <groupId>org.springframework.cloud</groupId>
  5. <artifactId>spring-cloud-dependencies</artifactId>
  6. <version>${spring-cloud.version}</version>
  7. <type>pom</type>
  8. <scope>import</scope>
  9. </dependency>
  10. </dependencies>
  11. </dependencyManagement>
  12.  
  13. <dependency>
  14. <groupId>org.springframework.cloud</groupId>
  15. <artifactId>spring-cloud-starter-openfeign</artifactId>
  16. </dependency>
  17.  
  18. <dependency>
  19. <groupId>io.github.openfeign</groupId>
  20. <artifactId>feign-okhttp</artifactId>
  21. </dependency>

2)、在配置文件中禁用默认的URLHttpConnection,启动okhttp

  1. feign.httpclient.enabled=false
  2. feign.okhttp.enabled=true

3)、其实这个时候就可以使用okhttp了

但网络上大部分博客还写了一个自定义配置类,在其中实例化了一个okhttp3.OkHttpClient,就是这么一个配置类导致了大坑啊,有了它之后okhttp根本不会生效,不信咱们就是来试一下

  1. @Configuration
  2. @ConditionalOnClass(Feign.class)
  3. @AutoConfigureBefore(FeignAutoConfiguration.class)
  4. public class OkHttpConfig {
  5. @Bean
  6. public okhttp3.OkHttpClient okHttpClient(){
  7. return new okhttp3.OkHttpClient.Builder()
  8. //设置连接超时
  9. .connectTimeout(10 , TimeUnit.SECONDS)
  10. //设置读超时
  11. .readTimeout(10 , TimeUnit.SECONDS)
  12. //设置写超时
  13. .writeTimeout(10 , TimeUnit.SECONDS)
  14. //是否自动重连
  15. .retryOnConnectionFailure(true)
  16. .connectionPool(new ConnectionPool(10 , 5L, TimeUnit.MINUTES))
  17. .build();
  18. }
  19. }

上面这个配置类其实就是配置了一下okhttp的基本参数和连接池的基本参数

此时我们可以在配置文件中开始日志打印,看一下那些自动配置没有生效

  1. debug=true

启动我们的项目可以在控制台搜索到如下日志输出

  1. FeignAutoConfiguration.OkHttpFeignConfiguration:
  2. Did not match:
  3. - @ConditionalOnBean (types: okhttp3.OkHttpClient; SearchStrategy: all) found beans of type 'okhttp3.OkHttpClient' okHttpClient (OnBeanCondition)
  4. Matched:
  5. - @ConditionalOnClass found required class 'feign.okhttp.OkHttpClient'; @ConditionalOnMissingClass did not find unwanted class 'com.netflix.loadbalancer.ILoadBalancer' (OnClassCondition)
  6. - @ConditionalOnProperty (feign.okhttp.enabled) matched (OnPropertyCondition)

从日志中可以清楚的看到FeignAutoConfiguration.OkHttpFeignConfiguration没有匹配成功(Did not match),原因也很简单是因为容器中已经存在了okhttp3.OkHttpClient对象,我们去看看这个配置类的源码,其中类上标注了@ConditionalOnMissingBean(okhttp3.OkHttpClient.class),意思上当容器中不存在okhttp3.OkHttpClient对象时才生效,然后我们却在自定义的配置类中画蛇添足的实例化了一个该对象到容器中。

  1. @Configuration(proxyBeanMethods = false)
  2. @ConditionalOnClass(OkHttpClient.class)
  3. @ConditionalOnMissingClass("com.netflix.loadbalancer.ILoadBalancer")
  4. @ConditionalOnMissingBean(okhttp3.OkHttpClient.class)
  5. @ConditionalOnProperty("feign.okhttp.enabled")
  6. protected static class OkHttpFeignConfiguration {
  7. private okhttp3.OkHttpClient okHttpClient;
  8. @Bean
  9. @ConditionalOnMissingBean(ConnectionPool.class)
  10. public ConnectionPool httpClientConnectionPool(
  11. FeignHttpClientProperties httpClientProperties,
  12. OkHttpClientConnectionPoolFactory connectionPoolFactory) {
  13. Integer maxTotalConnections = httpClientProperties.getMaxConnections();
  14. Long timeToLive = httpClientProperties.getTimeToLive();
  15. TimeUnit ttlUnit = httpClientProperties.getTimeToLiveUnit();
  16. return connectionPoolFactory.create(maxTotalConnections, timeToLive, ttlUnit);
  17. }
  18.  
  19. @Bean
  20. public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory,
  21. ConnectionPool connectionPool,
  22. FeignHttpClientProperties httpClientProperties) {
  23. Boolean followRedirects = httpClientProperties.isFollowRedirects();
  24. Integer connectTimeout = httpClientProperties.getConnectionTimeout();
  25. Boolean disableSslValidation = httpClientProperties.isDisableSslValidation();
  26. this.okHttpClient = httpClientFactory.createBuilder(disableSslValidation)
  27. .connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
  28. .followRedirects(followRedirects).connectionPool(connectionPool)
  29. .build();
  30. return this.okHttpClient;
  31. }
  32.  
  33. @PreDestroy
  34. public void destroy() {
  35. if (this.okHttpClient != null) {
  36. this.okHttpClient.dispatcher().executorService().shutdown();
  37. this.okHttpClient.connectionPool().evictAll();
  38. }
  39. }
  40.  
  41. @Bean
  42. @ConditionalOnMissingBean(Client.class)
  43. public Client feignClient(okhttp3.OkHttpClient client) {
  44. return new OkHttpClient(client);
  45. }
  46. }

4)、该如何处理才能使okhttp生效

其中我们的自定义配置类中并没有做什么特别复杂的事情,仅仅是给okhttp3.OkHttpClient和它的连接池对象设置了几个参数罢了,看看上面OkHttpFeignConfiguration类中实例化的几个类对象,其中就包含了okhttp3.OkHttpClient和ConnectionPool,从代码中不难看出它们的参数值都是从FeignHttpClientProperties获取的,因此我们只需要在配置文件中配上feign.httpclient开头的相关配置就可以了生效了。

如果我们的目的不仅仅是简单的修改几个参数值,比如需要在okhttp中添加拦截器Interceptor,这也非常简单,只需要写一个Interceptor的实现类,然后将OkHttpFeignConfiguration的内容完全复制一份到我们自定义的配置类中,并设置okhttp3.OkHttpClient的拦截器即可。

  1. import okhttp3.Interceptor;
  2. import okhttp3.Response;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import java.io.IOException;
  6. public class MyOkhttpInterceptor implements Interceptor {
  7. Logger logger = LoggerFactory.getLogger(MyOkhttpInterceptor.class);
  8. @Override
  9. public Response intercept(Chain chain) throws IOException {
  10. logger.info("okhttp method:{}",chain.request().method());
  11. logger.info("okhttp request:{}",chain.request().body());
  12. return chain.proceed(chain.request());
  13. }
  14. }

将自定义配置类中原有的内容去掉,复制一份OkHttpFeignConfiguration的代码做简单的修改,设置拦截器的代码如下

  1. @Bean
  2. public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory,
  3. ConnectionPool connectionPool,
  4. FeignHttpClientProperties httpClientProperties) {
  5. Boolean followRedirects = httpClientProperties.isFollowRedirects();
  6. Integer connectTimeout = httpClientProperties.getConnectionTimeout();
  7. Boolean disableSslValidation = httpClientProperties.isDisableSslValidation();
  8. this.okHttpClient = httpClientFactory.createBuilder(disableSslValidation)
  9. .connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
  10. .followRedirects(followRedirects).connectionPool(connectionPool)
  11. //这里设置我们自定义的拦截器
  12. .addInterceptor(new MyOkhttpInterceptor())
  13. .build();
  14. return this.okHttpClient;
  15. }

3、最后上两张图,Feign的动态代理使用和处理流程

基于Feign使用okhttp的填坑之旅

基于Feign使用okhttp的填坑之旅

补充:spring cloud feign sentinel okhttp3 gzip 压缩问题

引入pom okhttp 配置,okhttp使用连接池技术,相对feign httpUrlConnection 每次请求,创建一个连接,效率更高

  1. <dependency>
  2. <groupId>io.github.openfeign</groupId>
  3. <artifactId>feign-okhttp</artifactId>
  4. </dependency>

okhttp 开始压缩条件

基于Feign使用okhttp的填坑之旅

增加拦截器动态删除Accept-Encoding 参数,使okhttp压缩生效

  1. @Slf4j
  2. public class HttpOkInterceptor implements Interceptor {
  3. @Override
  4. public Response intercept(Chain chain) throws IOException {
  5. Request originRequest = chain.request();
  6. Response response = null;
  7. if (StringUtils.isNotEmpty(originRequest.header("Accept-Encoding"))) {
  8. Request request = originRequest.newBuilder().removeHeader("Accept-Encoding").build();
  9.  
  10. long doTime = System.nanoTime();
  11. response = chain.proceed(request);
  12. long currentTime = System.nanoTime();
  13. if(response != null) {
  14. ResponseBody responseBody = response.peekBody(1024 * 1024);
  15. LogUtil.info(log, String.format("接收响应: [%s] %n返回json:【%s】 %.1fms%n%s",
  16. response.request().url(),
  17. responseBody.string(),
  18. (currentTime - doTime) / 1e6d,
  19. response.headers()));
  20. }else {
  21. String encodedPath = originRequest.url().encodedPath();
  22. LogUtil.info(log, String.format("接收响应: [%s] %n %.1fms%n",
  23. encodedPath,
  24. (currentTime - doTime) / 1e6d));
  25. }
  26. }
  27. return response;
  28. }
  29. }

feign 配置

  1. feign:
  2. sentinel:
  3. # 开启Sentinel对Feign的支持
  4. enabled: true
  5. httpclient:
  6. enabled: false
  7. okhttp:
  8. enabled: true

feign 配置类

  1. @Configuration
  2. @ConditionalOnClass(Feign.class)
  3. @AutoConfigureBefore(FeignAutoConfiguration.class)
  4. public class FeignOkHttpConfig {
  5. @Bean
  6. public okhttp3.OkHttpClient okHttpClient(){
  7. return new okhttp3.OkHttpClient.Builder()
  8. //设置连接超时
  9. .connectTimeout(10, TimeUnit.SECONDS)
  10. //设置读超时
  11. .readTimeout(10, TimeUnit.SECONDS)
  12. //设置写超时
  13. .writeTimeout(10, TimeUnit.SECONDS)
  14. //是否自动重连
  15. .retryOnConnectionFailure(true)
  16. .connectionPool(new ConnectionPool(10, 5L, TimeUnit.MINUTES))
  17. .build();
  18. }
  19. }

案例:feign client

  1. @FeignClient(name = "服务名称",fallbackFactory = FeignFallBack.class ,url = "调试地址", configuration =FeignConfiguration.class)
  2. public interface FeignService {
  3. @RequestMapping(value = "/test/updateXx", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
  4. public ResponseEntity<byte[]> updateXx(@RequestBody XxVo xXVo);
  5. }

不知为啥 sentinel feign默认http,对压缩支持不好,使用okhttp 代替实现

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。如有错误或未考虑完全的地方,望不吝赐教。

原文链接:https://blog.csdn.net/eric520zenobia/article/details/103547552

标签:

相关文章

热门资讯

yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
2021德云社封箱演出完整版 2021年德云社封箱演出在线看
2021德云社封箱演出完整版 2021年德云社封箱演出在线看 2021-03-15
返回顶部