当前位置: 首页 > news >正文

Spring Cloud全解析:服务调用之OpenFeign集成OkHttp


文章目录

    • OpenFeign集成OkHttp
      • 添加依赖
      • 配置连接池
      • yml配置


OpenFeign集成OkHttp

OpenFeign本质是HTTP来进行服务调用的,也就是需要集成一个Http客户端。

使用的是Client接口来进行请求的

public interface Client {// request是封装的请求方式、参数、返回值类型// options 是连接超时、读取超时等的配置项Response execute(Request request, Options options) throws IOException;
}

默认是HttpURLConnection方式,也就是jdk中提供的最原始的那个

public static class Default implements Client {@Overridepublic Response execute(Request request, Options options) throws IOException {HttpURLConnection connection = convertAndSend(request, options);return convertResponse(connection).toBuilder().request(request).build();}
}

HTTP连接需要进行TCP三次握手,是一个比较耗时的操作,一般我们不直接使用HttpURLConnection,而是使用HttpClient/okHttp等支持连接池的客户端工具,以Feign集成OkHttp为例

添加依赖

        <dependency><groupId>io.github.openfeign</groupId><artifactId>feign-okhttp</artifactId></dependency>

其包内有一个Client的实现类OkHttpClient,

public final class OkHttpClient implements Client {@Overridepublic feign.Response execute(feign.Request input, feign.Request.Options options)throws IOException {okhttp3.OkHttpClient requestScoped;if (delegate.connectTimeoutMillis() != options.connectTimeoutMillis()|| delegate.readTimeoutMillis() != options.readTimeoutMillis()) {requestScoped = delegate.newBuilder().connectTimeout(options.connectTimeoutMillis(), TimeUnit.MILLISECONDS).readTimeout(options.readTimeoutMillis(), TimeUnit.MILLISECONDS).followRedirects(options.isFollowRedirects()).build();} else {requestScoped = delegate;}Request request = toOkHttpRequest(input);Response response = requestScoped.newCall(request).execute();return toFeignResponse(response, input).toBuilder().request(input).build();}
}

配置连接池

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;@Configuration
public class OkHttpConfig {/*** OkHttp 客户端配置** @return OkHttp 客户端配*/@Beanpublic OkHttpClient okHttpClient() {return new OkHttpClient.Builder().sslSocketFactory(sslSocketFactory(), x509TrustManager()).hostnameVerifier(hostnameVerifier()).retryOnConnectionFailure(false)    //是否开启缓存.connectionPool(pool())             //连接池.connectTimeout(15L, TimeUnit.SECONDS) // 连接超时时间.readTimeout(15L, TimeUnit.SECONDS) // 读取超时时间.followRedirects(true) // 是否允许重定向.build();}/*** 忽略证书校验** @return 证书信任管理器*/@Beanpublic X509TrustManager x509TrustManager() {return new X509TrustManager() {@Overridepublic void checkClientTrusted(X509Certificate[] x509Certificates, String s) {}@Overridepublic void checkServerTrusted(X509Certificate[] x509Certificates, String s) {}@Overridepublic X509Certificate[] getAcceptedIssuers() {return new X509Certificate[0];}};}/*** 信任所有 SSL 证书** @return*/@Beanpublic SSLSocketFactory sslSocketFactory() {try {TrustManager[] trustManagers = new TrustManager[]{x509TrustManager()};SSLContext sslContext = SSLContext.getInstance("SSL");sslContext.init(null, trustManagers, new SecureRandom());return sslContext.getSocketFactory();} catch (NoSuchAlgorithmException | KeyManagementException e) {e.printStackTrace();}return null;}/*** 连接池配置** @return 连接池*/@Beanpublic ConnectionPool pool() {// 最大连接数、连接存活时间、存活时间单位(分钟)return new ConnectionPool(200, 5, TimeUnit.MINUTES);}/*** 信任所有主机名** @return 主机名校验*/@Beanpublic HostnameVerifier hostnameVerifier() {return (s, sslSession) -> true;}
}

yml配置

要开启OkHttp ,还需要在YML 中添加开启配置项,默认是关闭的

feign:okhttp:enabled: true

至于为什么需要配这个,看一下FeignAutoConfiguration中装配OkHttp的条件

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(OkHttpClient.class)
@ConditionalOnMissingClass("com.netflix.loadbalancer.ILoadBalancer")
@ConditionalOnMissingBean(okhttp3.OkHttpClient.class)
@ConditionalOnProperty("feign.okhttp.enabled")
protected static class OkHttpFeignConfiguration

参考文献

  • OpenFeign集成OkHttp
http://www.lryc.cn/news/452724.html

相关文章:

  • 前端算法合集-1(含面试题)
  • 影刀---如何进行自动化操作
  • 146. LRU 缓存【 力扣(LeetCode) 】
  • 【算法】链表:92.反转链表(medium)+双指针
  • Command | Ubuntu 个别实用命令记录(新建用户、查看网速等)
  • 云服务器部署k8s需要什么配置?
  • Linux --入门学习笔记
  • 并发编程三大特性(原子性、可见性、有序性)
  • 物理学基础精解【41】
  • 深入理解Linux内核网络(一):内核接收数据包的过程
  • mysql学习教程,从入门到精通,SQL LIKE 运算符(28)
  • uniapp微信小程序使用ucharts遮挡自定义tabbar的最佳解决方案
  • C初阶(八)选择结构(分支结构)--if、else、switch
  • 基于Springboot vue应急物资供应管理系统设计与实现
  • 区块链+Web3学习笔记
  • Redis: 集群高可用之节点与插槽管理
  • HUAWEI New4.9G 与 2.6G 无法正常切换问题处理案例
  • Qt C++设计模式->责任链模式
  • paypal支付v2.0(php)支付代码
  • 基于Python的自然语言处理系列(23):DrQA
  • 誉天Linux云计算课程学什么?为什么保障就业?
  • 无人机控制和飞行、路径规划技术分析
  • 【C++】模拟实现红黑树
  • 离线安装docker
  • MySQL高阶2066-账户余额
  • 《RabbitMQ篇》Centos7安装RabbitMQ
  • 昇思学习打卡营第31天|深度解密 CycleGAN 图像风格迁移:从草图到线稿的无缝转化
  • 跟我学C++中级篇——空值的定义
  • (三)Mysql 数据库系统全解析
  • SAP HCM 0001信息类型一个月内有多个成本中心