Spring Cloud源码分析——Feign声明式服务调用

Spring Cloud源码分析——Feign声明式服务调用_第1张图片
IZONE nako酱好可爱

疫情现在比较稳定了,小区楼下每天该遛狗的遛狗、该买菜的买菜、该逛街的逛街。然而我眉头一皱,现在还是得紧绷神经、严守家里,打好攻坚防疫战(真的不是我宅)。上篇Ribbon的文章,朋友反馈还不错,今天又来挖新坑了。本文对Feign声明式服务调用进行简单分析(参考了翟永超[程序猿DD])的《Spring Cloud微服务实战》
参考文章:
深入理解Feign之源码解析
Spring Cloud Feign设计原理
SpringCloud | SpringCloud Feign的前世今生【源码深入分析】

上篇分析Ribbon讲到,一般会使用它对RestTemplate的请求拦截来实现对依赖服务的接口调用,而RestTemplate已经实现了对HTTP请求的封装处理,形成了一套模板化的调用方法。实际开发中,对服务依赖的调用肯定不止一处,再加上RestTemplate的封装,几乎每一次调用都是重复简单的模板化内容。Spring Cloud Feign应运而生,它在此基础上做了更进一步的封装,由它来定义实现依赖服务接口。高度概括就是,Feign封装了Http调用流程,更符合面向接口开发的习惯。

在Spring Cloud Feign的实现下,只需创建接口并通过注解的方式来配置它,即可完成对服务提供方的接口绑定,从而简化了在使用Spring Cloud Ribbon时自行封装服务调用客户端的开发量。Feign具备可插拔的注解支持,包括Feign注解和JAX-RS注解。并且还扩展了对Spring MVC的注解支持,对习惯Spring MVC的开发者非常友好。另外,Feign自身一些主要组件,比如解码器和编码器等,也以可插拔的方式提供,需要的时候可以方便更换或扩展。
对Feign大致了解之后,本文就以下方面进行源码分析:

  • 包扫描@FeignClient注解的类,获取相关信息注入IOC容器中
  • 通过JDK代理生成具体的RequestTemplate,RequestTemplate再生成Request
  • Client处理Request
  • Client结合Ribbon负载均衡

1、FeignClientsRegistrar源码

    @Override
    public void registerBeanDefinitions(AnnotationMetadata metadata,
            BeanDefinitionRegistry registry) {
        registerDefaultConfiguration(metadata, registry);
        registerFeignClients(metadata, registry);
    }

启动带有@EnableFeignClients注解的项目类,会进入到FeignClientsRegistrar类中的registerBeanDefinitions方法,可以看到其中调用了registerDefaultConfiguration(注册默认配置)和registerFeignClients(扫描Feign客户端)

private void registerDefaultConfiguration(AnnotationMetadata metadata,
            BeanDefinitionRegistry registry) {
        Map defaultAttrs = metadata
                .getAnnotationAttributes(EnableFeignClients.class.getName(), true);

        if (defaultAttrs != null && defaultAttrs.containsKey("defaultConfiguration")) {
            String name;
            if (metadata.hasEnclosingClass()) {
                name = "default." + metadata.getEnclosingClassName();
            }
            else {
                name = "default." + metadata.getClassName();
            }
            registerClientConfiguration(registry, name,
                    defaultAttrs.get("defaultConfiguration"));
        }
    }

FeignClientsRegistrar类中的registerDefaultConfiguration函数会检查是否有@EnableFeignClients注解,如果有,则调用registerClientConfiguration方法,注册客户端默认配置。

private void registerClientConfiguration(BeanDefinitionRegistry registry, Object name,
            Object configuration) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder
                .genericBeanDefinition(FeignClientSpecification.class);
        builder.addConstructorArgValue(name);
        builder.addConstructorArgValue(configuration);
        registry.registerBeanDefinition(
                name + "." + FeignClientSpecification.class.getSimpleName(),
                builder.getBeanDefinition());
    }

registerClientConfiguration方法将bean配置类包装成FeignClientSpecification类,注入到IOC容器中。划个小重点,这个方法非常重要,它包括了FeignClient中的重试策略、超时策略、日志等配置。如果某个服务没有配置,则采用默认配置。

接着,来看下扫描FeignClient。

public void registerFeignClients(AnnotationMetadata metadata,
            BeanDefinitionRegistry registry) {
        ClassPathScanningCandidateComponentProvider scanner = getScanner();
        scanner.setResourceLoader(this.resourceLoader);

        Set basePackages;

        Map attrs = metadata
                .getAnnotationAttributes(EnableFeignClients.class.getName());
        AnnotationTypeFilter annotationTypeFilter = new AnnotationTypeFilter(
                FeignClient.class);
        final Class[] clients = attrs == null ? null
                : (Class[]) attrs.get("clients");
        if (clients == null || clients.length == 0) {
            scanner.addIncludeFilter(annotationTypeFilter);
            basePackages = getBasePackages(metadata);
        }
        else {
            final Set clientClasses = new HashSet<>();
            basePackages = new HashSet<>();
            for (Class clazz : clients) {
                basePackages.add(ClassUtils.getPackageName(clazz));
                clientClasses.add(clazz.getCanonicalName());
            }
            AbstractClassTestingTypeFilter filter = new AbstractClassTestingTypeFilter() {
                @Override
                protected boolean match(ClassMetadata metadata) {
                    String cleaned = metadata.getClassName().replaceAll("\\$", ".");
                    return clientClasses.contains(cleaned);
                }
            };
            scanner.addIncludeFilter(
                    new AllTypeFilter(Arrays.asList(filter, annotationTypeFilter)));
        }

        for (String basePackage : basePackages) {
            Set candidateComponents = scanner
                    .findCandidateComponents(basePackage);
            for (BeanDefinition candidateComponent : candidateComponents) {
                if (candidateComponent instanceof AnnotatedBeanDefinition) {
                    // verify annotated class is an interface
                    AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent;
                    AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();
                    Assert.isTrue(annotationMetadata.isInterface(),
                            "@FeignClient can only be specified on an interface");

                    Map attributes = annotationMetadata
                            .getAnnotationAttributes(
                                    FeignClient.class.getCanonicalName());

                    String name = getClientName(attributes);
                    registerClientConfiguration(registry, name,
                            attributes.get("configuration"));

                    registerFeignClient(registry, annotationMetadata, attributes);
                }
            }
        }
    }

registerFeignClients(这个方法有加s)方法扫描被@FeignClient注解修饰的接口。将注解的信息annotationMetadata取出,包括类名,一并赋给beanDefinitionBuilder,再生成beanDefinition,注入到IOC容器中。

registerFeignClients(这个方法有加s)方法继续走下去,会执行registerFeignClient(这个方法没有加s)方法。

private void registerFeignClient(BeanDefinitionRegistry registry,
            AnnotationMetadata annotationMetadata, Map attributes) {
        String className = annotationMetadata.getClassName();
        BeanDefinitionBuilder definition = BeanDefinitionBuilder
                .genericBeanDefinition(FeignClientFactoryBean.class);
        validate(attributes);
        definition.addPropertyValue("url", getUrl(attributes));
        definition.addPropertyValue("path", getPath(attributes));
        String name = getName(attributes);
        definition.addPropertyValue("name", name);
        definition.addPropertyValue("type", className);
        definition.addPropertyValue("decode404", attributes.get("decode404"));
        definition.addPropertyValue("fallback", attributes.get("fallback"));
        definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);

        String alias = name + "FeignClient";
        AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();
        beanDefinition.setPrimary(true);
        BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className,
                new String[] { alias });
        BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
    }

registerFeignClient(这个方法没有加s)中有一句代码要划下重点。

BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(FeignClientFactoryBean.class);

很明显,扫描出来的注解信息赋于BeanDefinitionBuilder,同时BeanDefinitionBuilder为FeignClientFactoryBean类型,FeignClientFactoryBean又继承FactoryBean。可推理出,FeignClient其实是用Spring代理工厂来生成代理类。
以上,扫描结束。

2.ReflectiveFeign源码

public  T newInstance(Target target) {
    Map nameToHandler = targetToHandlersByName.apply(target);
    Map methodToHandler = new LinkedHashMap();
    List defaultMethodHandlers = new LinkedList();

    for (Method method : target.type().getMethods()) {
      if (method.getDeclaringClass() == Object.class) {
        continue;
      } else if(Util.isDefault(method)) {
        DefaultMethodHandler handler = new DefaultMethodHandler(method);
        defaultMethodHandlers.add(handler);
        methodToHandler.put(method, handler);
      } else {
        methodToHandler.put(method, nameToHandler.get(Feign.configKey(target.type(), method)));
      }
    }
    InvocationHandler handler = factory.create(target, methodToHandler);
    T proxy = (T) Proxy.newProxyInstance(target.type().getClassLoader(), new Class[]{target.type()}, handler);

    for(DefaultMethodHandler defaultMethodHandler : defaultMethodHandlers) {
      defaultMethodHandler.bindTo(proxy);
    }
    return proxy;
  }

注入Bean之后,ReflectiveFeign中根据接口类和Contract协议解析方式,解析接口类上的方法和注解,转换成内部的MethodHandler处理方式,再将所有请求(已处理为MethodHandler)转换给InvocationHandler,再通过JDK代理,将InvocationHandler动态生成代理实例。
紧接着,刚刚处理的代理实例会被SynchronousMethodHandler类进行拦截处理。

 @Override
  public Object invoke(Object[] argv) throws Throwable {
    RequestTemplate template = buildTemplateFromArgs.create(argv);
    Retryer retryer = this.retryer.clone();
    while (true) {
      try {
        return executeAndDecode(template);
      } catch (RetryableException e) {
        retryer.continueOrPropagate(e);
        if (logLevel != Logger.Level.NONE) {
          logger.logRetry(metadata.configKey(), logLevel);
        }
        continue;
      }
    }
  }

从源码可以看出,被拦截之后,其中参数会被处理成RequestTemplate,接着调用executeAndDecode方法

Object executeAndDecode(RequestTemplate template) throws Throwable {
    Request request = targetRequest(template);

    if (logLevel != Logger.Level.NONE) {
      logger.logRequest(metadata.configKey(), logLevel, request);
    }

    Response response;
    long start = System.nanoTime();
    try {
      response = client.execute(request, options);
    } catch (IOException e) {
      if (logLevel != Logger.Level.NONE) {
        logger.logIOException(metadata.configKey(), logLevel, e, elapsedTime(start));
      }
      throw errorExecuting(request, e);
    }
    long elapsedTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);

    boolean shouldClose = true;
    try {
      if (logLevel != Logger.Level.NONE) {
        response =
            logger.logAndRebufferResponse(metadata.configKey(), logLevel, response, elapsedTime);
      }
      if (Response.class == metadata.returnType()) {
        if (response.body() == null) {
          return response;
        }
        if (response.body().length() == null ||
                response.body().length() > MAX_RESPONSE_BUFFER_SIZE) {
          shouldClose = false;
          return response;
        }
        // Ensure the response body is disconnected
        byte[] bodyData = Util.toByteArray(response.body().asInputStream());
        return Response.create(response.status(), response.reason(), response.headers(), bodyData);
      }
      if (response.status() >= 200 && response.status() < 300) {
        if (void.class == metadata.returnType()) {
          return null;
        } else {
          return decode(response);
        }
      } else if (decode404 && response.status() == 404) {
        return decoder.decode(response, metadata.returnType());
      } else {
        throw errorDecoder.decode(metadata.configKey(), response);
      }
    } catch (IOException e) {
      if (logLevel != Logger.Level.NONE) {
        logger.logIOException(metadata.configKey(), logLevel, e, elapsedTime);
      }
      throw errorReading(request, response, e);
    } finally {
      if (shouldClose) {
        ensureClosed(response.body());
      }
    }
  }

executeAndDecode方法简单概括就两句

Request request = targetRequest(template)
response = client.execute(request, options);

通过RequestTemplate生成Request,再用Client执行获取Response

3、Client源码

Client组件是非常重要的部分,Feign最终发送Request以及接收Response都是在Client中完成的。Client实现中的Default方法由HttpURLConnnection实现网络请求,同时还支持HttpClient、Okhttp。这些都可以配置文件中进行更换。
本节就分析Client其中一个实现FeignRibbonClient,先从它的自动配置类FeignRibbonClientAutoConfiguration下手

    @Bean
    @ConditionalOnMissingBean
    public Client feignClient(CachingSpringLoadBalancerFactory cachingFactory,
            SpringClientFactory clientFactory) {
        return new LoadBalancerFeignClient(new Client.Default(null, null),
                cachingFactory, clientFactory);
    }

FeignRibbonClientAutoConfiguration中feignClient实现的是LoadBalancerFeignClient类。源码中Client.Default采用默认配置,即用HttpURLConnnection网络请求框架。

4、LoadBalancerFeignClient源码

@Override
    public Response execute(Request request, Request.Options options) throws IOException {
        try {
            URI asUri = URI.create(request.url());
            String clientName = asUri.getHost();
            URI uriWithoutHost = cleanUrl(request.url(), clientName);
            FeignLoadBalancer.RibbonRequest ribbonRequest = new FeignLoadBalancer.RibbonRequest(
                    this.delegate, request, uriWithoutHost);

            IClientConfig requestConfig = getClientConfig(options, clientName);
            return lbClient(clientName).executeWithLoadBalancer(ribbonRequest,
                    requestConfig).toResponse();
        }
        catch (ClientException e) {
            IOException io = findIOException(e);
            if (io != null) {
                throw io;
            }
            throw new RuntimeException(e);
        }
    }

源码中FeignClient将Request封装成RibbonRequest,再执行executeWithLoadBalancer方法。

public T executeWithLoadBalancer(final S request, final IClientConfig requestConfig) throws ClientException {
        RequestSpecificRetryHandler handler = getRequestSpecificRetryHandler(request, requestConfig);
        LoadBalancerCommand command = LoadBalancerCommand.builder()
                .withLoadBalancerContext(this)
                .withRetryHandler(handler)
                .withLoadBalancerURI(request.getUri())
                .build();

        try {
            return command.submit(
                new ServerOperation() {
                    @Override
                    public Observable call(Server server) {
                        URI finalUri = reconstructURIWithServer(server, request.getUri());
                        S requestForServer = (S) request.replaceUri(finalUri);
                        try {
                            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);
            }
        }
        
    }

很明显,是通过ribbon负载均衡的方式处理Request请求,并返回Response响应。跟进去最后一步command.submit。里面有段关键的代码:

// Use the load balancer
        Observable o = 
                (server == null ? selectServer() : Observable.just(server))
                .concatMap(new Func1>() {
\\以下省略

再跟进去selectServer的代码:

private Observable selectServer() {
        return Observable.create(new OnSubscribe() {
            @Override
            public void call(Subscriber next) {
                try {
                    Server server = loadBalancerContext.getServerFromLoadBalancer(loadBalancerURI, loadBalancerKey);   
                    next.onNext(server);
                    next.onCompleted();
                } catch (Exception e) {
                    next.onError(e);
                }
            }
        });
    }

从源码中,可以很明显看出,调用了loadBalancerContext负载均衡客户端中选择服务,接下去的流程也就是上篇Ribbon的内容了。

简单概括下Feign的实现过程:

  1. 首先开启@EnableFeignClients注解,再根据Feign规则,用@FeignClient修饰接口;
  2. 程序启动后,会进行包扫描,检查所有被@FeignClient修饰的接口,获取注解等信息,并注入到IOC容器中;
  3. 当接口被调用时,通过JDK代理,生成具体的RequestTemplate,再execute和Decode生成Request;
  4. Request交给Client处理并返回Response响应;
  5. Client被封装为LoadBalanceClient类,该类结合Ribbon实现负载均衡。

Feign源码分析就到这里了,本文知识点较为抽象、信息量比较大,读者需要多花些心思去阅读,再加上调试源码加深理解。后面可能会不定期更新,有兴趣的朋友可以在评论区一起讨论研究。

最后有件很重要的事,那就是麻烦点赞关注赞赏,谢谢(๑•̀ㅂ•́)و✧

你可能感兴趣的:(Spring Cloud源码分析——Feign声明式服务调用)