OpenFeign中的HttpClient替换
OpenFeign中的HttpClient如果不做任何特殊的配置,默认是采用JDK自带的HttpURLConnection发送HTTP请求,由于JDK的HttpURLConnection没有连接池,性能和效率上是比较低的。
例如当我们遇到连接超时的错误时,也能看到是HttpURLConnection
抛出的异常~这也能进一步证明默认采用的是HttpURLConnection
。
另外官方也建议我们使用Apache HttpClient 5
如下图
因此实际开发中,切换成Apache HttpClient 5
是很有必要的。
引入依赖
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents.client5/httpclient5 -->
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.github.openfeign/feign-hc5 -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-hc5</artifactId>
<!--如果SpringBoot2.x版本的这里版本要换成11.x的-->
<version>13.3</version>
</dependency>
开启配置说明
feign:
httpclient:
hc5:
enabled: true # 这是2.x的写法
client:
config:
default:
connectTimeout: 2000
readTimeout: 2000
# --------------- 以下是SpringBoot 3.0 写法 ---------------
spring:
application:
name: dist-service
cloud:
openfeign:
httpclient:
hc5:
enabled: true
再来看超时的报错,已经全部是HttpClient 5