- 引入pom okhttp 配置,okhttp使用连接池技术,相对feign httpUrlConnection 每次请求,创建一个连接,效率更高
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
- okhttp 开始压缩条件
![](https://i-blog.csdnimg.cn/blog_migrate/2806f1de529de88450cd8d9e92ed7d40.png)
- 增加拦截器动态删除Accept-Encoding 参数,使okhttp压缩生效
@Slf4j
public class HttpOkInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request originRequest = chain.request();
Response response = null;
if (StringUtils.isNotEmpty(originRequest.header("Accept-Encoding"))) {
Request request = originRequest.newBuilder().removeHeader("Accept-Encoding").build();
long doTime = System.nanoTime();
response = chain.proceed(request);
long currentTime = System.nanoTime();
if(response != null) {
ResponseBody responseBody = response.peekBody(1024 * 1024);
LogUtil.info(log, String.format("接收响应: [%s] %n返回json:【%s】 %.1fms%n%s",
response.request().url(),
responseBody.string(),
(currentTime - doTime) / 1e6d,
response.headers()));
}else {
String encodedPath = originRequest.url().encodedPath();
LogUtil.info(log, String.format("接收响应: [%s] %n %.1fms%n",
encodedPath,
(currentTime - doTime) / 1e6d));
}
}
return response;
}
}
feign:
sentinel:
# 开启Sentinel对Feign的支持
enabled: true
httpclient:
enabled: false
okhttp:
enabled: true
@Configuration
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
public class FeignOkHttpConfig {
@Bean
public okhttp3.OkHttpClient okHttpClient(){
return new okhttp3.OkHttpClient.Builder()
//设置连接超时
.connectTimeout(10, TimeUnit.SECONDS)
//设置读超时
.readTimeout(10, TimeUnit.SECONDS)
//设置写超时
.writeTimeout(10, TimeUnit.SECONDS)
//是否自动重连
.retryOnConnectionFailure(true)
.connectionPool(new ConnectionPool(10, 5L, TimeUnit.MINUTES))
.build();
}
}
@FeignClient(name = "服务名称",fallbackFactory = FeignFallBack.class ,url = "调试地址", configuration =FeignConfiguration.class)
public interface FeignService {
@RequestMapping(value = "/test/updateXx", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<byte[]> updateXx(@RequestBody XxVo xXVo);
}