手记

Spring Cloud OpenFeign调用流程

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

调用流程

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

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 文件中,做了配置

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.cloud.openfeign.loadbalancer.FeignLoadBalancerAutoConfiguration

FeignLoadBalancerAutoConfiguration 中引入 DefaultFeignLoadBalancerConfiguration

@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 中

@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

@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 ,我们它有哪些属性:

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 方法,我们看一下:

@Override
public void close() {
  Util.ensureClosed(body);
}

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

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

Http响应处理

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

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,而我们需要的是一个对象,比如:

@FeignClient(
        value = "openfeign-goods-service",
        path = "/goods"
)
public interface IGoodsFeignClient {

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

}
0人推荐
随时随地看视频
慕课网APP