国产片侵犯亲女视频播放_亚洲精品二区_在线免费国产视频_欧美精品一区二区三区在线_少妇久久久_在线观看av不卡

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達式|C/C++|IOS|C#|Swift|Android|JavaScript|易語言|

服務(wù)器之家 - 編程語言 - Java教程 - 基于Feign使用okhttp的填坑之旅

基于Feign使用okhttp的填坑之旅

2021-08-13 13:41石楠煙斗的霧 Java教程

這篇文章主要介紹了基于Feign使用okhttp的填坑之旅,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

1、由于項目需要遠程調(diào)用http請求

因此就想到了Feign,因為真的非常的方便,只需要定義一個接口就行。

但是feign默認使用的JDK的URLHttpConnection,沒有連接池效率不好,從Feign的自動配置類FeignAutoConfiguration中可以看到Feign除了默認的http客戶端還支持okhttp和ApacheHttpClient,我這里選擇了okhttp,它是有連接池的。

2、看看網(wǎng)絡(luò)上大部分博客中是怎么使用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了

但網(wǎng)絡(luò)上大部分博客還寫了一個自定義配置類,在其中實例化了一個okhttp3.OkHttpClient,就是這么一個配置類導(dǎo)致了大坑啊,有了它之后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. //設(shè)置連接超時
  9. .connectTimeout(10 , TimeUnit.SECONDS)
  10. //設(shè)置讀超時
  11. .readTimeout(10 , TimeUnit.SECONDS)
  12. //設(shè)置寫超時
  13. .writeTimeout(10 , TimeUnit.SECONDS)
  14. //是否自動重連
  15. .retryOnConnectionFailure(true)
  16. .connectionPool(new ConnectionPool(10 , 5L, TimeUnit.MINUTES))
  17. .build();
  18. }
  19. }

上面這個配置類其實就是配置了一下okhttp的基本參數(shù)和連接池的基本參數(shù)

此時我們可以在配置文件中開始日志打印,看一下那些自動配置沒有生效

  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),原因也很簡單是因為容器中已經(jīng)存在了okhttp3.OkHttpClient對象,我們?nèi)タ纯催@個配置類的源碼,其中類上標注了@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生效

其中我們的自定義配置類中并沒有做什么特別復(fù)雜的事情,僅僅是給okhttp3.OkHttpClient和它的連接池對象設(shè)置了幾個參數(shù)罷了,看看上面OkHttpFeignConfiguration類中實例化的幾個類對象,其中就包含了okhttp3.OkHttpClient和ConnectionPool,從代碼中不難看出它們的參數(shù)值都是從FeignHttpClientProperties獲取的,因此我們只需要在配置文件中配上feign.httpclient開頭的相關(guān)配置就可以了生效了。

如果我們的目的不僅僅是簡單的修改幾個參數(shù)值,比如需要在okhttp中添加攔截器Interceptor,這也非常簡單,只需要寫一個Interceptor的實現(xiàn)類,然后將OkHttpFeignConfiguration的內(nèi)容完全復(fù)制一份到我們自定義的配置類中,并設(shè)置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. }

將自定義配置類中原有的內(nèi)容去掉,復(fù)制一份OkHttpFeignConfiguration的代碼做簡單的修改,設(shè)置攔截器的代碼如下

  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. //這里設(shè)置我們自定義的攔截器
  12. .addInterceptor(new MyOkhttpInterceptor())
  13. .build();
  14. return this.okHttpClient;
  15. }

3、最后上兩張圖,F(xiàn)eign的動態(tài)代理使用和處理流程

基于Feign使用okhttp的填坑之旅

基于Feign使用okhttp的填坑之旅

補充:spring cloud feign sentinel okhttp3 gzip 壓縮問題

引入pom okhttp 配置,okhttp使用連接池技術(shù),相對feign httpUrlConnection 每次請求,創(chuàng)建一個連接,效率更高

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

okhttp 開始壓縮條件

基于Feign使用okhttp的填坑之旅

增加攔截器動態(tài)刪除Accept-Encoding 參數(shù),使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("接收響應(yīng): [%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("接收響應(yīng): [%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. //設(shè)置連接超時
  9. .connectTimeout(10, TimeUnit.SECONDS)
  10. //設(shè)置讀超時
  11. .readTimeout(10, TimeUnit.SECONDS)
  12. //設(shè)置寫超時
  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 = "服務(wù)名稱",fallbackFactory = FeignFallBack.class ,url = "調(diào)試地址", 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 代替實現(xiàn)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持我們。如有錯誤或未考慮完全的地方,望不吝賜教。

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

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 青青在线精品视频 | 羞羞网址| 综合在线视频 | 精品久久久久久久久久久久久久 | 欧美不卡视频 | 自拍偷拍欧美 | 亚洲视频中文字幕 | 国产一级毛片一级 | 欧美日本在线观看 | 久久99国产精品久久99大师 | 毛片在线免费播放 | 日韩电影一区二区三区 | 黄色影院在线观看 | 最新国产在线 | 欧美日韩一区精品 | 中文字幕视频在线观看 | 精品国产999 | 国产成人片| 国产亚洲一区二区三区 | 91久久精品一区二区二区 | 性做久久久久久 | 天天操天天干天天插 | 老女肥熟av免费观看 | 1000部精品久久久久久久久 | 午夜高清视频 | 国产精品久久久久久久久久久久久久 | 久久久成人网 | 午夜在线观看视频网站 | 午夜视频免费 | 91精品国产一区二区三区免费 | 日韩中文字幕在线 | 国产精品美女久久久久久久网站 | 中文字幕视频免费 | 精品成人在线 | 毛片aaa | 日韩有码av | 日韩在线免费视频 | 欧美a级网站 | 亚洲精品短视频 | 国产精品久久久久久久久福交 | 精品久久亚洲 |