乐趣区

关于springcloud:Spring-Cloud-OpenFeign调用流程

上一节给大家分享了 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

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

我是 Erwin Feng,一个专一于高质量编程的开发者。如果你对我内容感兴趣,能够关注我的微信公众号【Erwin Feng】,能够第一工夫收到更新推送!

退出移动版