热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

SpringCloudfeign客户端执行流程概述

概述应用程序初始化之后,开发人员定义的每个feign客户端对应一个ReflectiveFeign$FeignInvocationHan

概述

应用程序初始化之后,开发人员定义的每个feign客户端对应一个 ReflectiveFeign$FeignInvocationHandler实例。实例具体创建的过程可以参考文章"注解 @EnableFeignClients 工作原理"。本文仅分析一个方法请求发生时,一个feign客户端如何将其转换成最终的远程服务调用并处理响应,涉及以下几个问题点:

  1. feign方法和服务的对应
  2. 选用哪个服务节点
  3. 发起服务请求和接收响应
  4. 处理服务响应

源代码分析


1. feign方法和服务的对应

实际上,在初始化过程中创建feign客户端实例时,已经完成了feign方法和服务对应,从最终生成的实例所包含的信息就可以看得出来。

比如feign客户端定义如下 :

package xxx;
import com.google.common.collect.Maps;
import xxx.TestModel;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(name = "test-service", path = "/test")
public interface TestService {
@GetMapping(value = "/echo")
TestModel echoGet(@RequestParam("parameter") String parameter);
@PostMapping(value = "/echo/post",consumes = {
"application/x-www-form-urlencoded"})
TestModel echoPostForm(Map formParams);
@PostMapping(value = "/echo/post")
TestModel echoPost(@RequestParam("parameter") String parameter);
}

则最终生成的客户端实例会如下所示 :

this = {
ReflectiveFeign$FeignInvocationHandler@5249}
target = {
Target$HardCodedTarget@5257}
"HardCodedTarget(type=TestService, name=test-service, url=http://test-service/test)"
dispatch = {
LinkedHashMap@5258} size = 3
0 = {
LinkedHashMap$Entry@5290} "public abstract xxx.TestModel xxx.TestService.echoPostForm(java.util.Map)"
1 = {
LinkedHashMap$Entry@5291} "public abstract xxx.TestModel xxx.TestService.echoGet(java.lang.String)"
2 = {
LinkedHashMap$Entry@5292} "public abstract xxx.TestModel xxx.TestService.echoPost(java.lang.String)"

这里feign客户端实例的属性target指向了目标服务http://test-service/test,每个feign客户端方法的注解也指明了更进一步的url路径,比如方法echoGet最终会对应到http://test-service/test/echo,而方法echoPostForm/echoPost最终会对应到http://test-service/test/echo/post。而dispatch是一个Map,keyfeign客户端的方法,value实现类则是SynchronousMethodHandler,它也包含了和属性target一样的信息以及对应方法上的元数据。

有了上述信息,一旦某个客户端方法被调用,就相当于调用了dispatch中对应方法的SynchronousMethodHandler:

// 内部类 ReflectiveFeign$FeignInvocationHandler 方法
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ("equals".equals(method.getName())) {
try {
Object otherHandler =
args.length > 0 && args[0] != null ? Proxy.getInvocationHandler(args[0]) : null;
return equals(otherHandler);
} catch (IllegalArgumentException e) {
return false;
}
} else if ("hashCode".equals(method.getName())) {
return hashCode();
} else if ("toString".equals(method.getName())) {
return toString();
}
// 对 feign client 方法的调用最终转换成dispatch中对应方法的SynchronousMethodHandler的调用
return dispatch.get(method).invoke(args);
}

由此可见,当feign客户端的某个服务方法被调用时,对应的SynchronousMethodHandler#invoke会被调用。而SynchronousMethodHandler已经掌握了定位目标服务所需要的几乎所有的信息。目前尚不清楚的是,如果使用了负载均衡,test-service会最终对应哪个服务节点呢?

2. 选用哪个服务节点

带着上述问题,我们继续来看 SynchronousMethodHandler#invoke方法的执行 :

  1. 构建RequestTemplate

    这里构造RequestTemplate使用了一个RequestTemplate.Factory buildTemplateFromArgs,该对象是通过SynchronousMethodHandler构造函数传入的 ,所构造的RequestTemplate对象会包含来自接口方法定义上的path属性,http method属性,参数等,但是还不包含目标服务节点信息。

    对于上面例子中提到的三个方法,生成的RequestTemplate的请求分别是 :

    echoGet :
    URL : http://test-service/test/echo?parameter=GET%20request
    Body : []
    echoPost :
    URL : http://test-service/test/echo/post?parameter=POST%20request
    Body : []
    echoPostForm :
    URL : http://test-service/test/echo/post
    Content Type : application/x-www-form-urlencoded
    Body : [parameter=POST+FORM+request]

  2. #executeAndDecode上面所构建的RequestTemplate
    1. 应用请求拦截器RequestInterceptor和应用目标到RestTemplate形成一个Request对象

      此时RestTemplate已经拥有除了具体服务节点之外所有的请求信息了。

    2. 调用LoadBalancerFeignClient#execute

      这里LoadBalancerFeignClient 是通过SynchronousMethodHandler构造函数传入的

  3. RetryableException异常的话进行一次重试处理

上面流程 SynchronousMethodHandler#invoke最终调用LoadBalancerFeignClient#execute :

  1. 构建请求对象FeignLoadBalancer.RibbonRequest ribbonRequest
  2. 获取请求配置 IClientConfig requestConfig

    IClientConfig requestConfig = getClientConfig(options, clientName)

  3. 获取针对当前服务名称的负载均衡器FeignLoadBalancer (注意这里使用了缓存机制)
  4. 调用所构建负载均衡器FeignLoadBalancer 的方法executeWithLoadBalancer

FeignLoadBalancer#executeWithLoadBalancer方法实现如下 :

public T executeWithLoadBalancer(final S request, final IClientConfig requestConfig)
throws ClientException {
// 构建一个LoadBalancerCommand对象
LoadBalancerCommand command = buildLoadBalancerCommand(request, requestConfig);
try {
// 构建一个ServerOperation并提交到所构建的LoadBalancerCommand
return command.submit(
new ServerOperation() {
@Override
public Observable call(Server server) {
// 例子输入 :
// server : localhost:8080 所选定的服务节点
// request.uri : http://test/echo?parameter=value 请求URL含参数,
// 不含主机端口部分
// 例子输出 :
// 最终可以用于发起请求的完整的URL finalUri :
// http://localhost:8080/test/echo?parameter=value
URI finalUri = reconstructURIWithServer(server, request.getUri());
S requestForServer = (S) request.replaceUri(finalUri);
try {
// 发起最终的服务请求和处理相应
// 实现在FeignLoadBalancer基类中,GET/POST等各种方法都会在这里被处理
return Observable.just(
AbstractLoadBalancerAwareClient.this.execute(
requestForServer, requestConfig));
}
catch (Exception e) {
return Observable.error(e);
}
}
})
.toBlocking()
.single();
} catch (Exception e) {
Throwable t = e.getCause();
if (t instanceof ClientException) {
throw (ClientException) t;
} else {
throw new ClientException(e);
}
}
}

上面的方法FeignLoadBalancer#executeWithLoadBalancer实现中,通过#buildLoadBalancerCommand方法构建了一个LoadBalancerCommand,它的#submit方法会从多个负载均衡服务节点中选出一个供这次调用使用,具体的选择逻辑实现在方法LoadBalancerCommand#selectServer中。

到此为止,我们就知道最重要使用哪个服务节点了。

接下来,我们看最终服务请求的发起和响应的接收。这部分逻辑实现在FeignLoadBalancer#execute中:


@Override
public RibbonResponse execute(RibbonRequest request, IClientConfig configOverride)
throws IOException {
Request.Options options;
if (configOverride != null) {
RibbonProperties override = RibbonProperties.from(configOverride);
options = new Request.Options(
override.connectTimeout(this.connectTimeout),
override.readTimeout(this.readTimeout));
}
else {
options = new Request.Options(this.connectTimeout, this.readTimeout);
}
Response response = request.client().execute(request.toRequest(), options);
return new RibbonResponse(request.getUri(), response);
}

3. 发起服务请求和接收响应

从上面代码可以看到,最终请求通过Response response = request.client().execute(request.toRequest(), options)发起并接收响应。而这部分具体实现在feign.Client接口的内部类Default:

package feign;
/** * Submits HTTP Request requests. Implementations are expected to be thread-safe. */
public interface Client {
/** * Executes a request against its Request#url() url and returns a response. * * @param request safe to replay. * @param options options to apply to this request. * @return connected response, Response.Body is absent or unread. * @throws IOException on a network error connecting to Request#url(). */
Response execute(Request request, Options options) throws IOException;
public static class Default implements Client {
private final SSLSocketFactory sslContextFactory;
private final HostnameVerifier hostnameVerifier;
/** * Null parameters imply platform defaults. */
public Default(SSLSocketFactory sslContextFactory, HostnameVerifier hostnameVerifier) {
this.sslContextFactory = sslContextFactory;
this.hostnameVerifier = hostnameVerifier;
}
@Override
public Response execute(Request request, Options options) throws IOException {
HttpURLConnection connection = convertAndSend(request, options);
return convertResponse(connection, request);
}
// 对服务节点发起`HTTP`请求
HttpURLConnection convertAndSend(Request request, Options options) throws IOException {
final HttpURLConnection connection =
(HttpURLConnection) new URL(request.url()).openConnection();
if (connection instanceof HttpsURLConnection) {
HttpsURLConnection sslCon = (HttpsURLConnection) connection;
if (sslContextFactory != null) {
sslCon.setSSLSocketFactory(sslContextFactory);
}
if (hostnameVerifier != null) {
sslCon.setHostnameVerifier(hostnameVerifier);
}
}
connection.setConnectTimeout(options.connectTimeoutMillis());
connection.setReadTimeout(options.readTimeoutMillis());
connection.setAllowUserInteraction(false);
connection.setInstanceFollowRedirects(options.isFollowRedirects());
connection.setRequestMethod(request.httpMethod().name());
Collection contentEncodingValues = request.headers().get(CONTENT_ENCODING);
boolean gzipEncodedRequest =
contentEncodingValues != null && contentEncodingValues.contains(ENCODING_GZIP);
boolean deflateEncodedRequest =
contentEncodingValues != null && contentEncodingValues.contains(ENCODING_DEFLATE);
boolean hasAcceptHeader = false;
Integer contentLength = null;
for (String field : request.headers().keySet()) {
if (field.equalsIgnoreCase("Accept")) {
hasAcceptHeader = true;
}
for (String value : request.headers().get(field)) {
if (field.equals(CONTENT_LENGTH)) {
if (!gzipEncodedRequest && !deflateEncodedRequest) {
contentLength = Integer.valueOf(value);
connection.addRequestProperty(field, value);
}
} else {
connection.addRequestProperty(field, value);
}
}
}
// Some servers choke on the default accept string.
if (!hasAcceptHeader) {
connection.addRequestProperty("Accept", "*/*");
}
if (request.body() != null) {
if (contentLength != null) {
connection.setFixedLengthStreamingMode(contentLength);
} else {
connection.setChunkedStreamingMode(8196);
}
connection.setDoOutput(true);
OutputStream out = connection.getOutputStream();
if (gzipEncodedRequest) {
out = new GZIPOutputStream(out);
} else if (deflateEncodedRequest) {
out = new DeflaterOutputStream(out);
}
try {
out.write(request.body());
} finally {
try {
out.close();
} catch (IOException suppressed) {
// NOPMD
}
}
}
return connection;
}
// 接收响应
Response convertResponse(HttpURLConnection connection, Request request) throws IOException {
int status = connection.getResponseCode();
String reason = connection.getResponseMessage();
if (status <0) {
throw new IOException(format("Invalid status(%s) executing %s %s", status,
connection.getRequestMethod(), connection.getURL()));
}
Map> headers &#61; new LinkedHashMap>();
for (Map.Entry> field : connection.getHeaderFields().entrySet()) {
// response message
if (field.getKey() !&#61; null) {
headers.put(field.getKey(), field.getValue());
}
}
Integer length &#61; connection.getContentLength();
if (length &#61;&#61; -1) {
length &#61; null;
}
InputStream stream;
if (status >&#61; 400) {
stream &#61; connection.getErrorStream();
} else {
stream &#61; connection.getInputStream();
}
return Response.builder()
.status(status)
.reason(reason)
.headers(headers)
.request(request)
.body(stream, length)
.build();
}
}
}

4. 处理服务响应

缺省情况下,Spring Cloud应用中feign客户端使用一个ResponseEntityDecoder来解析服务响应 :

package org.springframework.cloud.openfeign.support;
/** * Decoder adds compatibility for Spring MVC&#39;s ResponseEntity to any other decoder via * composition. * &#64;author chadjaros */
public class ResponseEntityDecoder implements Decoder {
private Decoder decoder;
public ResponseEntityDecoder(Decoder decoder) {
this.decoder &#61; decoder;
}
&#64;Override
public Object decode(final Response response, Type type) throws IOException,
FeignException {
if (isParameterizeHttpEntity(type)) {
type &#61; ((ParameterizedType) type).getActualTypeArguments()[0];
Object decodedObject &#61; decoder.decode(response, type);
return createResponse(decodedObject, response);
}
else if (isHttpEntity(type)) {
return createResponse(null, response);
}
else {
return decoder.decode(response, type);
}
}
private boolean isParameterizeHttpEntity(Type type) {
if (type instanceof ParameterizedType) {
return isHttpEntity(((ParameterizedType) type).getRawType());
}
return false;
}
private boolean isHttpEntity(Type type) {
if (type instanceof Class) {
Class c &#61; (Class) type;
return HttpEntity.class.isAssignableFrom(c);
}
return false;
}
&#64;SuppressWarnings("unchecked")
private ResponseEntity createResponse(Object instance, Response response) {
MultiValueMap headers &#61; new LinkedMultiValueMap<>();
for (String key : response.headers().keySet()) {
headers.put(key, new LinkedList<>(response.headers().get(key)));
}
return new ResponseEntity<>((T) instance, headers, HttpStatus.valueOf(response
.status()));
}
}

参考文章

注解 &#64;EnableFeignClients 工作原理


推荐阅读
  • 个人学习使用:谨慎参考1Client类importcom.thoughtworks.gauge.Step;importcom.thoughtworks.gauge.T ... [详细]
  • 如何使用Java获取服务器硬件信息和磁盘负载率
    本文介绍了使用Java编程语言获取服务器硬件信息和磁盘负载率的方法。首先在远程服务器上搭建一个支持服务端语言的HTTP服务,并获取服务器的磁盘信息,并将结果输出。然后在本地使用JS编写一个AJAX脚本,远程请求服务端的程序,得到结果并展示给用户。其中还介绍了如何提取硬盘序列号的方法。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • [大整数乘法] java代码实现
    本文介绍了使用java代码实现大整数乘法的过程,同时也涉及到大整数加法和大整数减法的计算方法。通过分治算法来提高计算效率,并对算法的时间复杂度进行了研究。详细代码实现请参考文章链接。 ... [详细]
  • 开发笔记:Java是如何读取和写入浏览器Cookies的
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了Java是如何读取和写入浏览器Cookies的相关的知识,希望对你有一定的参考价值。首先我 ... [详细]
  • Imtryingtofigureoutawaytogeneratetorrentfilesfromabucket,usingtheAWSSDKforGo.我正 ... [详细]
  • 基于Axis、XFire、CXF的webservice客户端调用示例
    本文介绍了如何使用Axis、XFire、CXF等工具来实现webservice客户端的调用,以及提供了使用Java代码进行调用的示例。示例代码中设置了服务接口类、地址,并调用了sayHello方法。 ... [详细]
  • 如何查询zone下的表的信息
    本文介绍了如何通过TcaplusDB知识库查询zone下的表的信息。包括请求地址、GET请求参数说明、返回参数说明等内容。通过curl方法发起请求,并提供了请求示例。 ... [详细]
  • 开发笔记:加密&json&StringIO模块&BytesIO模块
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了加密&json&StringIO模块&BytesIO模块相关的知识,希望对你有一定的参考价值。一、加密加密 ... [详细]
  • 本文介绍了Java工具类库Hutool,该工具包封装了对文件、流、加密解密、转码、正则、线程、XML等JDK方法的封装,并提供了各种Util工具类。同时,还介绍了Hutool的组件,包括动态代理、布隆过滤、缓存、定时任务等功能。该工具包可以简化Java代码,提高开发效率。 ... [详细]
  • 本文介绍了Web学习历程记录中关于Tomcat的基本概念和配置。首先解释了Web静态Web资源和动态Web资源的概念,以及C/S架构和B/S架构的区别。然后介绍了常见的Web服务器,包括Weblogic、WebSphere和Tomcat。接着详细讲解了Tomcat的虚拟主机、web应用和虚拟路径映射的概念和配置过程。最后简要介绍了http协议的作用。本文内容详实,适合初学者了解Tomcat的基础知识。 ... [详细]
  • 从零学Java(10)之方法详解,喷打野你真的没我6!
    本文介绍了从零学Java系列中的第10篇文章,详解了Java中的方法。同时讨论了打野过程中喷打野的影响,以及金色打野刀对经济的增加和线上队友经济的影响。指出喷打野会导致线上经济的消减和影响队伍的团结。 ... [详细]
  • flowable工作流 流程变量_信也科技工作流平台的技术实践
    1背景随着公司业务发展及内部业务流程诉求的增长,目前信息化系统不能够很好满足期望,主要体现如下:目前OA流程引擎无法满足企业特定业务流程需求,且移动端体 ... [详细]
  • 模板引擎StringTemplate的使用方法和特点
    本文介绍了模板引擎StringTemplate的使用方法和特点,包括强制Model和View的分离、Lazy-Evaluation、Recursive enable等。同时,还介绍了StringTemplate语法中的属性和普通字符的使用方法,并提供了向模板填充属性的示例代码。 ... [详细]
  • Java程序设计第4周学习总结及注释应用的开发笔记
    本文由编程笔记#小编为大家整理,主要介绍了201521123087《Java程序设计》第4周学习总结相关的知识,包括注释的应用和使用类的注释与方法的注释进行注释的方法,并在Eclipse中查看。摘要内容大约为150字,提供了一定的参考价值。 ... [详细]
author-avatar
耗子很傻爱钻洞
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有