pom.xml引入(务必在spring-cloud-starter-openfeign之前):
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-openfeign-core-asyn</artifactId> <version>3.0.8-SNAPSHOT</version> <scope>compile</scope> </dependency> <!-- 以及真异步通讯模块 --> <dependency> <groupId>io.github.openfeign</groupId> <artifactId>feign-hc5</artifactId> </dependency>
注解:@EnableFeignClientsWithAsync() 启动openfeign
配置添加(3.1版本不要配置 httpclient.hc5、okhttp、httpclient,否则可能启动失败):
feign: client: #启动异步(默认是同步的) asyn-enabled: true httpclient: hc5-async: #启用hc5的真异步通讯(默认是基于线程的伪异步) enabled: true
具体接口添加<CompletableFuture>即可,如下,如果是同步的一样可以用,只是纯同步
@RequestMapping(value ="/system/sysParam/paramValueAndDelaySecond/{paramName}", method = RequestMethod.GET)
CompletableFuture<Result<String>> paramValueAndDelaySecondAsyn(@PathVariable("paramName") String paramName, @RequestParam("seconds") Integer seconds);
自建添加http2 client:
@Bean
public CloseableHttpAsyncClient httpAsyncClient5http2(FeignHttpClientProperties httpClientProperties) {
log.info("CloseableHttpAsyncClient http2 1.0!");
IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(Timeout.ofMilliseconds(250)) // 1.1
.setSelectInterval(TimeValue.ofMilliseconds(50)) // 1.2
.setSoTimeout(Timeout.of(httpClientProperties.getHc5().getSocketTimeout(),
httpClientProperties.getHc5().getSocketTimeoutUnit()))
.build();
httpAsyncClient5 = HttpAsyncClients.customHttp2()
.disableCookieManagement()
.disableAutomaticRetries()
.useSystemProperties()
.setIOReactorConfig(ioReactorConfig)
.setDefaultRequestConfig(RequestConfig.custom()
.setRedirectsEnabled(httpClientProperties.isFollowRedirects())
.setConnectTimeout(100, TimeUnit.MILLISECONDS)
.build())
.build();
httpAsyncClient5.start();
return httpAsyncClient5;
}
后期通过属性支持支持http2
异步导致的结果是发送也是异步(接口返回其实请求还未发送完)
RequestConfig 中 connectionRequestTimeout,影响异步发送超时(目前设置在connectTimeout,即设置ConnectTimeout即可)
影响并发的吞吐量的maxConnPerRoute,maxConnTotal(http1),当设置为1的场景下,基本上就是一条条的发送接受(实际感受到的瞬发,但是结果是依次累加实际返回)
http2吞吐量不受maxConnPerRoute,maxConnTotal影响,但是使劲发可能会存在上游拥堵