前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring Cloud OpenFeign调用流程

Spring Cloud OpenFeign调用流程

原创
作者头像
冯文议
发布2022-11-21 21:39:43
5820
发布2022-11-21 21:39:43
举报
文章被收录于专栏:编程笔记编程笔记

上一节给大家分享了Spring Cloud OpenFeign的启动流程,接下来给大家分享一下调用流程。话不多说,咱们直接开始。

视频:https://www.bilibili.com/video/BV1A84y1C7XD/

调用流程

xxxFeignClient

→ feign.ReflectiveFeign.FeignInvocationHandler#invoke

→ feign.InvocationHandlerFactory.MethodHandler#invoke

→ feign.SynchronousMethodHandler#invoke

→ feign.SynchronousMethodHandler#executeAndDecode

→ org.springframework.cloud.openfeign.loadbalancer.FeignBlockingLoadBalancerClient#execute

→ feign.Client.Default#execute

→ feign.AsyncResponseHandler#handleResponse

动态代理

feign.ReflectiveFeign.FeignInvocationHandler#invoke

代码语言:java
复制
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  return dispatch.get(method).invoke(args);
}

这里说一下 dispatch 属性,它的类型是Map<Method, MethodHandler>意思是,可以通过方法找到对应的Handler,这样就可以进入到 SynchronousMethodHandler#invoke。

feign.SynchronousMethodHandler#executeAndDecode

从这个方法的名称也能看出来,这个是执行请求,并且实现解码的功能,这是一个核心的方法。

负载均衡

org.springframework.cloud.openfeign.loadbalancer.FeignBlockingLoadBalancerClient#execute

这个是实现均衡,实现将URL中服务名转成 真实的IP。

下面我们看看它是如何被自动注入的。

首先在 spring.factories 文件中,做了配置

代码语言:java
复制
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.cloud.openfeign.loadbalancer.FeignLoadBalancerAutoConfiguration

FeignLoadBalancerAutoConfiguration 中引入 DefaultFeignLoadBalancerConfiguration

代码语言:java
复制
@ConditionalOnClass(Feign.class)
@ConditionalOnBean({ LoadBalancerClient.class, LoadBalancerClientFactory.class })
@AutoConfigureBefore(FeignAutoConfiguration.class)
@AutoConfigureAfter({ BlockingLoadBalancerClientAutoConfiguration.class, LoadBalancerAutoConfiguration.class })
@EnableConfigurationProperties(FeignHttpClientProperties.class)
@Configuration(proxyBeanMethods = false)
// Order is important here, last should be the default, first should be optional
// see
// https://github.com/spring-cloud/spring-cloud-netflix/issues/2086#issuecomment-316281653
@Import({ HttpClientFeignLoadBalancerConfiguration.class, OkHttpFeignLoadBalancerConfiguration.class,
		HttpClient5FeignLoadBalancerConfiguration.class, DefaultFeignLoadBalancerConfiguration.class })
public class FeignLoadBalancerAutoConfiguration {

}

new FeignBlockingLoadBalancerClient,并且注入到 Spring Bean 中

代码语言:java
复制
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(LoadBalancerClientsProperties.class)
class DefaultFeignLoadBalancerConfiguration {

	@Bean
	@ConditionalOnMissingBean
	@Conditional(OnRetryNotEnabledCondition.class)
	public Client feignClient(LoadBalancerClient loadBalancerClient,
			LoadBalancerClientFactory loadBalancerClientFactory) {
		return new FeignBlockingLoadBalancerClient(new Client.Default(null, null), loadBalancerClient,
				loadBalancerClientFactory);
	}

}

Http请求

下面我们看看 feign 是如何实现 Http 请求的。

feign.Client.Default#execute

代码语言:java
复制
@Override
public Response execute(Request request, Options options) throws IOException {
  HttpURLConnection connection = convertAndSend(request, options);
  return convertResponse(connection, request);
}

主要就是在这个方法中,默认使用 jdk 实现 http请求。

convertAndSend,这个方法做了两件事,一是,打开 Http 连接,获取到 HttpURLConnection ,并设置相关属性;二是,如果有参数,就通过输出流(OutputStream)写入参数。

convertResponse,这个方法返回的是 feign.Response ,我们它有哪些属性:

代码语言:java
复制
public final class Response implements Closeable {

  private final int status;
  private final String reason;
  private final Map<String, Collection<String>> headers;
  private final Body body;
  private final Request request;
  private final ProtocolVersion protocolVersion;

}

首先,这里实现 Closeable 接口,所以必然有 close 方法,我们看一下:

代码语言:java
复制
@Override
public void close() {
  Util.ensureClosed(body);
}

好了,明白了,body实际上是写入流(InputStream)。

总结一下:这里实现了Http请求,上传了参数,或获得了输入流。

Http响应处理

看完了请求,我们再回到 feign.SynchronousMethodHandler#executeAndDecode,看下面的代码

代码语言:java
复制
CompletableFuture<Object> resultFuture = new CompletableFuture<>();
asyncResponseHandler.handleResponse(resultFuture, metadata.configKey(), response,
    metadata.returnType(),
    elapsedTime);

try {
  if (!resultFuture.isDone())
    throw new IllegalStateException("Response handling not done");

  return resultFuture.join();
} catch (CompletionException e) {
  Throwable cause = e.getCause();
  if (cause != null)
    throw cause;
  throw e;
}

这里是通过 CompletableFuture,来装配响应结果。

feign.AsyncResponseHandler#handleResponse,这个方法就也就是处理Http响应结果的入口。

比如要判断状态码,获取结果,关闭输入流等。

响应结果解码

解码流程如下:

feign.AsyncResponseHandler#decode

→ org.springframework.cloud.openfeign.support.ResponseEntityDecoder#decode

→ org.springframework.cloud.openfeign.support.SpringDecoder#decode

→ org.springframework.cloud.openfeign.support.SpringDecoder.FeignResponseAdapter#FeignResponseAdapter

→ org.springframework.web.client.HttpMessageConverterExtractor#extractData

→ org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter#read

为什么需要解码呢?

http响应的结果类型是String,而我们需要的是一个对象,比如:

代码语言:java
复制
@FeignClient(
        value = "openfeign-goods-service",
        path = "/goods"
)
public interface IGoodsFeignClient {

    @GetMapping("/list")
    ResultTemplate<ListTemplate<GoodsModel>> list();

}

我是 Erwin Feng,一个专注于高质量编程的开发者。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 调用流程
  • 动态代理
  • 负载均衡
  • Http请求
  • Http响应处理
  • 响应结果解码
相关产品与服务
负载均衡
负载均衡(Cloud Load Balancer,CLB)提供安全快捷的流量分发服务,访问流量经由 CLB 可以自动分配到云中的多台后端服务器上,扩展系统的服务能力并消除单点故障。负载均衡支持亿级连接和千万级并发,可轻松应对大流量访问,满足业务需求。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com