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

news/2024/10/4 17:20:07/

文章目录

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


OpenFeign集成OkHttp

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

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

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

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

java">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,

java">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();}
}

配置连接池

java">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的条件

java">@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.ppmy.cn/news/1534531.html

相关文章

Linux编译部署PHP环境

1.准备工作 安装前我们需要设置防护墙&#xff0c;开放端口&#xff0c;更新yum源 # 1.防火墙 systemctl status firewalld 看到active(running)就意味着防火墙打开了 systemctl stop firewalld 看到inactive(dead)就意味着防火墙关闭了 systemctl start fire…

Java中的对象生命周期管理:从Spring Bean到JVM对象的深度解析

Java中的对象生命周期管理&#xff1a;从Spring Bean到JVM对象的深度解析 大家好&#xff0c;我是微赚淘客返利系统3.0的小编&#xff0c;是个冬天不穿秋裤&#xff0c;天冷也要风度的程序猿&#xff01;今天我们来聊聊Java中的对象生命周期管理&#xff0c;尤其是从Spring Be…

Flux 最新最快ControlNet模型现身:法线贴图详细测评

原文链接&#xff1a;Flux目前最快ControlNet模型现身&#xff01;法线贴图详细测评 (chinaz.com) Flux目前最快ControlNet模型现身&#xff01; 上周一个名叫JasperAI的团队开源了他们的 3 款Flux ControlNet&#xff0c;分别是法线贴图&#xff0c;深度&#xff0c;和升频器…

Spring Web是个什么东西

Spring Web是Spring框架的一部分&#xff0c;主要用于构建Web应用程序。它提供了一系列功能&#xff0c;帮助开发者处理Web请求和响应&#xff0c;包括&#xff1a; 1. Spring MVC 实现了MVC&#xff08;模型-视图-控制器&#xff09;设计模式&#xff0c;支持请求的处理、视…

【STM32】【rt-thread】C函数调用

C函数调用 一、基本概念二、函数调用2.1 函数调用2.2 参数传递2.3 栈帧创建2.3.1 保存旧FP2.3.2 更新FP和SP2.3.3 保存调用者状态 三、函数执行3.1 局部变量分配3.2 执行代码 四、返回过程4.1 返回值4.2 恢复栈帧4.2.1 恢复FP4.2.2 恢复SP 4.3 返回地址五、继续执行六、参考 一…

Spring Boot 3.x 集成 Feign

在Spring Boot 3.x中集成Feign&#xff0c;可以大大简化微服务之间的HTTP调用。以下是关于Spring Boot 3.x集成Feign的详细步骤和说明&#xff1a; 一、Feign简介 Feign是一个声明式的HTTP客户端&#xff0c;它使得编写Web服务客户端变得更加简单。使用Feign&#xff0c;可以通…

【Linux系统编程】第二十七弹---文件描述符与重定向:fd奥秘、dup2应用与Shell重定向实战

✨个人主页&#xff1a; 熬夜学编程的小林 &#x1f497;系列专栏&#xff1a; 【C语言详解】 【数据结构详解】【C详解】【Linux系统编程】 目录 1、文件描述符fd 1.1、0 & 1 & 2 1.2、文件描述符的分配规则 2、重定向 3、使用 dup2 系统调用 3.1、> 输出…

Ubuntu2404安装

Ubuntu是一款非常优秀的发行版本&#xff0c;起初她的优势主要在于桌面版&#xff0c;但是随着Centos 从服务版的支持的退出&#xff0c;Ubuntu server也在迅猛的成长&#xff0c;并且不断收获了用户&#xff0c;拥有了一大批忠实的粉丝。好了&#xff0c;废话不多说&#xff0…