跟我学SpringCloud | 第二十章:Spring Cloud 之 okhttp
1. 什么是 okhttp ?
okhttp 是由 square 公司开源的一个 http 客户端。在 Java 平台上,Java 标准库提供了 HttpURLConnection 类来支持 HTTP 通讯。不过 HttpURLConnection 本身的 API 不够友好,所提供的功能也有限。大部分 Java 程序都选择使用 Apache 的开源项目 HttpClient 作为 HTTP 客户端。Apache HttpClient 库的功能强大,使用率也很高。
2. 为什么要使用 okhttp ?
okhttp 的设计初衷就是简单和高效,这也是我们选择它的重要原因之一。它的优势如下:
- 支持 HTTP/2 协议。
- 允许连接到同一个主机地址的所有请求,提高请求效率。
- 共享Socket,减少对服务器的请求次数。
- 通过连接池,减少了请求延迟。
- 缓存响应数据来减少重复的网络请求。
- 减少了对数据流量的消耗。
- 自动处理GZip压缩。
3. 实战目标
- Feign 中使用 okhttp 替代 httpclient
- Zuul 中使用 okhttp 替代 httpclient
4. 在 Feign 中使用 okhttp
首先介绍一下工程结构,本演示工程包含 provider-server、consumer-server、eureka-server 和 zuul-server 。
4.1 consumer-server 依赖 pom.xml 如下:
代码清单:chapter19/consumer-server/pom.xml
***
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <dependency> <groupId>io.github.openfeign</groupId> <artifactId>feign-okhttp</artifactId> </dependency> </dependencies>
feign-okhttp
这里无需指定版本,目前引入的feign-okhttp
版本为 10.2.3 ,而okhttp
的版本为 3.8.1 ,如图:
4.2 配置文件 application.yml
代码清单:chapter19/consumer-server/src/main/resources/application.yml
***
feign: httpclient: enabled: false okhttp: enabled: true
- 在配置文件中需关闭 feign 对 httpclient 的使用并开启 okhttp 。
4.3 配置类 OkHttpConfig.java
代码清单:chapter19/consumer-server/src/main/java/com/springcloud/consumerserver/config/OkHttpConfig.java
***
@Configuration @ConditionalOnClass(Feign.class) @AutoConfigureBefore(FeignAutoConfiguration.class) public class OkHttpConfig { @Bean public OkHttpClient okHttpClient(){ return new OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .retryOnConnectionFailure(true) .connectionPool(new ConnectionPool(10 , 5L, TimeUnit.MINUTES)) .addInterceptor(new OkHttpLogInterceptor()) .build(); } }
- 在配置类中将
OkHttpClient
注入 Spring 的容器中,这里我们指定了连接池的大小,最大保持连接数为 10 ,并且在 5 分钟不活动之后被清除。