springcloud 入门 5 (feign源码分析)

feign:(推荐使用)

  Feign是受到Retrofit,JAXRS-2.0和WebSocket的影响,它是一个jav的到http客户端绑定的开源项目。 Feign的主要目标是将Java Http 客户端变得简单.减少配置文件,实现基于注解零配置调用

源码分析:

  feign的实现:

   1>启动类加注解:@EnableFeignClients

    

   2> feign实现:

    

   3> 接口调用 

    

  这是feign的实现过程:这是代码实现,注意还需要配置文件,又不懂的参考我博客 springcloud 入门 3 (服务之间的调用)

源码层次:

  1>源码入口:@FeignClient

   

  note:在正式进入源码之前,我先介绍一个包:spring-cloud-openfeign-core.后面所有的源码基本上都在这个包里。为啥我要先介绍一下呢。因为以前总说feign整合了ribbon,那我们从哪看出来呢?

  下面我来带大家看一下包结构就清楚了。

    

   剩下的自己可以更进一步去追源码,看是怎么封装整合的!在这我就不往下追了,

  2> Feign源码实现:

     FeignClient的配置

      默认的配置类为FeignClientsConfiguration,这个类在spring-cloud-netflix-core的jar包下,打开这个类,可以发现它是一个配置类,注入了很多的相关配置的bean,包括      feignRetryer、FeignLoggerFactory、FormattingConversionService等,其中还包括了Decoder、Encoder、Contract,如果这三个bean在没有注入的情况下,会自动注入默认的配置。

  • Decoder feignDecoder: ResponseEntityDecoder(这是对SpringDecoder的封装)
  • Encoder feignEncoder: SpringEncoder
  • Logger feignLogger: Slf4jLogger
  • Contract feignContract: SpringMvcContract
  • Feign.Builder feignBuilder: HystrixFeign.Builder

  

  

  Feign的工作原理

     feign是一个伪客户端,即它不做任何的请求处理。Feign通过处理注解生成request,从而实现简化HTTP API开发的目的,即开发人员可以使用注解的方式定制request api模板,在发送http request请求之前,feign通过处理注解的方式替换掉request模板中的参数,这种实现方式显得更为直接、可理解。通过包扫描注入FeignClient的bean,该源码在FeignClientsRegistrar类: 

首先在启动配置上检查是否有@EnableFeignClients注解,如果有该注解,则开启包扫描,扫描被@FeignClient注解接口

  

 1 private void registerDefaultConfiguration(AnnotationMetadata metadata,
 2             BeanDefinitionRegistry registry) {
 3         Map<String, Object> defaultAttrs = metadata
 4                 .getAnnotationAttributes(EnableFeignClients.class.getName(), true);
 5 
 6         if (defaultAttrs != null && defaultAttrs.containsKey("defaultConfiguration")) {
 7             String name;
 8             if (metadata.hasEnclosingClass()) {
 9                 name = "default." + metadata.getEnclosingClassName();
10             }
11             else {
12                 name = "default." + metadata.getClassName();
13             }
14             registerClientConfiguration(registry, name,
15                     defaultAttrs.get("defaultConfiguration"));
16         }
17     }

 

 

程序启动后通过包扫描,当类有@FeignClient注解,将注解的信息取出,连同类名一起取出,赋给BeanDefinitionBuilder,然后根据BeanDefinitionBuilder得到beanDefinition,最后beanDefinition式注入到ioc容器中,源码如下:

 1 public void registerFeignClients(AnnotationMetadata metadata,
 2             BeanDefinitionRegistry registry) {
 3         ClassPathScanningCandidateComponentProvider scanner = getScanner();
 4         scanner.setResourceLoader(this.resourceLoader);
 5 
 6         Set<String> basePackages;
 7 
 8         Map<String, Object> attrs = metadata
 9                 .getAnnotationAttributes(EnableFeignClients.class.getName());
10         AnnotationTypeFilter annotationTypeFilter = new AnnotationTypeFilter(
11                 FeignClient.class);
12         final Class<?>[] clients = attrs == null ? null
13                 : (Class<?>[]) attrs.get("clients");
14         if (clients == null || clients.length == 0) {
15             scanner.addIncludeFilter(annotationTypeFilter);
16             basePackages = getBasePackages(metadata);
17         }
18         else {
19             final Set<String> clientClasses = new HashSet<>();
20             basePackages = new HashSet<>();
21             for (Class<?> clazz : clients) {
22                 basePackages.add(ClassUtils.getPackageName(clazz));
23                 clientClasses.add(clazz.getCanonicalName());
24             }
25             AbstractClassTestingTypeFilter filter = new AbstractClassTestingTypeFilter() {
26                 @Override
27                 protected boolean match(ClassMetadata metadata) {
28                     String cleaned = metadata.getClassName().replaceAll("\\$", ".");
29                     return clientClasses.contains(cleaned);
30                 }
31             };
32             scanner.addIncludeFilter(
33                     new AllTypeFilter(Arrays.asList(filter, annotationTypeFilter)));
34         }
35 
36         for (String basePackage : basePackages) {
37             Set<BeanDefinition> candidateComponents = scanner
38                     .findCandidateComponents(basePackage);
39             for (BeanDefinition candidateComponent : candidateComponents) {
40                 if (candidateComponent instanceof AnnotatedBeanDefinition) {
41                     // verify annotated class is an interface
42                     AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent;
43                     AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();
44                     Assert.isTrue(annotationMetadata.isInterface(),
45                             "@FeignClient can only be specified on an interface");
46 
47                     Map<String, Object> attributes = annotationMetadata
48                             .getAnnotationAttributes(
49                                     FeignClient.class.getCanonicalName());
50 
51                     String name = getClientName(attributes);
52                     registerClientConfiguration(registry, name,
53                             attributes.get("configuration"));
54 
55                     registerFeignClient(registry, annotationMetadata, attributes);
56                 }
57             }
58         }
59     }
60 
61 
62 private void registerFeignClient(BeanDefinitionRegistry registry,
63             AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {
64         String className = annotationMetadata.getClassName();
65         BeanDefinitionBuilder definition = BeanDefinitionBuilder
66                 .genericBeanDefinition(FeignClientFactoryBean.class);
67         validate(attributes);
68         definition.addPropertyValue("url", getUrl(attributes));
69         definition.addPropertyValue("path", getPath(attributes));
70         String name = getName(attributes);
71         definition.addPropertyValue("name", name);
72         definition.addPropertyValue("type", className);
73         definition.addPropertyValue("decode404", attributes.get("decode404"));
74         definition.addPropertyValue("fallback", attributes.get("fallback"));
75         definition.addPropertyValue("fallbackFactory", attributes.get("fallbackFactory"));
76         definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
77 
78         String alias = name + "FeignClient";
79         AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();
80 
81         boolean primary = (Boolean)attributes.get("primary"); // has a default, won't be null
82 
83         beanDefinition.setPrimary(primary);
84 
85         String qualifier = getQualifier(attributes);
86         if (StringUtils.hasText(qualifier)) {
87             alias = qualifier;
88         }
89 
90         BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className,
91                 new String[] { alias });
92         BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
93     }

 

 

注入bean之后,通过jdk的代理,当请求Feign Client的方法时会被拦截,代码在ReflectiveFeign类,代码如下:

 1  public <T> T newInstance(Target<T> target) {
 2     Map<String, MethodHandler> nameToHandler = targetToHandlersByName.apply(target);
 3     Map<Method, MethodHandler> methodToHandler = new LinkedHashMap<Method, MethodHandler>();
 4     List<DefaultMethodHandler> defaultMethodHandlers = new LinkedList<DefaultMethodHandler>();
 5 
 6     for (Method method : target.type().getMethods()) {
 7       if (method.getDeclaringClass() == Object.class) {
 8         continue;
 9       } else if(Util.isDefault(method)) {
10         DefaultMethodHandler handler = new DefaultMethodHandler(method);
11         defaultMethodHandlers.add(handler);
12         methodToHandler.put(method, handler);
13       } else {
14         methodToHandler.put(method, nameToHandler.get(Feign.configKey(target.type(), method)));
15       }
16     }
17     InvocationHandler handler = factory.create(target, methodToHandler);
18     T proxy = (T) Proxy.newProxyInstance(target.type().getClassLoader(), new Class<?>[]{target.type()}, handler);
19 
20     for(DefaultMethodHandler defaultMethodHandler : defaultMethodHandlers) {
21       defaultMethodHandler.bindTo(proxy);
22     }
23     return proxy;
24   }

 

在SynchronousMethodHandler类进行拦截处理,当被FeignClient的方法被拦截会根据参数生成RequestTemplate对象,该对象就是http请求的模板,代码如下:

 @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;
      }
    }
  }

 

其中有个executeAndDecode()方法,该方法是通RequestTemplate生成Request请求对象,然后根据用client获取response。

Object executeAndDecode(RequestTemplate template) throws Throwable {
    Request request = targetRequest(template);
    ...//省略代码
    response = client.execute(request, options);
    ...//省略代码

}

 

Client组件

其中Client组件是一个非常重要的组件,Feign最终发送request请求以及接收response响应,都是由Client组件完成的,其中Client的实现类,只要有Client.Default,该类由HttpURLConnnection实现网络请求,另外还支持HttpClient、Okhttp.

首先来看以下在FeignRibbonClient的自动配置类,FeignRibbonClientAutoConfiguration ,主要在工程启动的时候注入一些bean,其代码如下:

@ConditionalOnClass({ ILoadBalancer.class, Feign.class })
@Configuration
@AutoConfigureBefore(FeignAutoConfiguration.class)
public class FeignRibbonClientAutoConfiguration {

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

}

 

在缺失配置feignClient的情况下,会自动注入new Client.Default(),跟踪Client.Default()源码,它使用的网络请求框架为HttpURLConnection,代码如下:

1 @Override
2     public Response execute(Request request, Options options) throws IOException {
3       HttpURLConnection connection = convertAndSend(request, options);
4       return convertResponse(connection).toBuilder().request(request).build();
5     }

 

 

怎么在feign中使用HttpClient,查看FeignRibbonClientAutoConfiguration的源码

 1 @ConditionalOnClass({ ILoadBalancer.class, Feign.class })
 2 @Configuration
 3 @AutoConfigureBefore(FeignAutoConfiguration.class)
 4 public class FeignRibbonClientAutoConfiguration {
 5 ...//省略代码
 6 
 7 @Configuration
 8     @ConditionalOnClass(ApacheHttpClient.class)
 9     @ConditionalOnProperty(value = "feign.httpclient.enabled", matchIfMissing = true)
10     protected static class HttpClientFeignLoadBalancedConfiguration {
11 
12         @Autowired(required = false)
13         private HttpClient httpClient;
14 
15         @Bean
16         @ConditionalOnMissingBean(Client.class)
17         public Client feignClient(CachingSpringLoadBalancerFactory cachingFactory,
18                 SpringClientFactory clientFactory) {
19             ApacheHttpClient delegate;
20             if (this.httpClient != null) {
21                 delegate = new ApacheHttpClient(this.httpClient);
22             }
23             else {
24                 delegate = new ApacheHttpClient();
25             }
26             return new LoadBalancerFeignClient(delegate, cachingFactory, clientFactory);
27         }
28     }
29 
30 ...//省略代码
31 }

 

 

从代码@ConditionalOnClass(ApacheHttpClient.class)注解可知道,只需要在pom文件加上HttpClient的classpath就行了,另外需要在配置文件上加上feign.httpclient.enabled为true,从 @ConditionalOnProperty注解可知,这个可以不写,在默认的情况下就为true.

在pom文件加上:


<dependency>
    <groupId>com.netflix.feign</groupId>
    <artifactId>feign-httpclient</artifactId>
    <version>RELEASE</version>
</dependency>

 

同理,如果想要feign使用Okhttp,则只需要在pom文件上加上feign-okhttp的依赖:

<dependency>
    <groupId>com.netflix.feign</groupId>
    <artifactId>feign-okhttp</artifactId>
    <version>RELEASE</version>
</dependency>

feign的负载均衡是怎么样实现的呢?

通过上述的FeignRibbonClientAutoConfiguration类配置Client的类型(httpurlconnection,okhttp和httpclient)时候,可知最终向容器注入的是LoadBalancerFeignClient,即负载均衡客户端。现在来看下LoadBalancerFeignClient的代码:

 1  @Override
 2     public Response execute(Request request, Request.Options options) throws IOException {
 3         try {
 4             URI asUri = URI.create(request.url());
 5             String clientName = asUri.getHost();
 6             URI uriWithoutHost = cleanUrl(request.url(), clientName);
 7             FeignLoadBalancer.RibbonRequest ribbonRequest = new FeignLoadBalancer.RibbonRequest(
 8                     this.delegate, request, uriWithoutHost);
 9 
10             IClientConfig requestConfig = getClientConfig(options, clientName);
11             return lbClient(clientName).executeWithLoadBalancer(ribbonRequest,
12                     requestConfig).toResponse();
13         }
14         catch (ClientException e) {
15             IOException io = findIOException(e);
16             if (io != null) {
17                 throw io;
18             }
19             throw new RuntimeException(e);
20         }
21     }

 

其中有个executeWithLoadBalancer()方法,即通过负载均衡的方式请求。

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

        try {
            return command.submit(
                new ServerOperation<T>() {
                    @Override
                    public Observable<T> 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);
            }
        }

    }   

 

 

其中服务在submit()方法上,点击submit进入具体的方法,这个方法是LoadBalancerCommand的方法:

 Observable<T> o = 
                (server == null ? selectServer() : Observable.just(server))
                .concatMap(new Func1<Server, Observable<T>>() {
                    @Override
                    // Called for each server being selected
                    public Observable<T> call(Server server) {
                        context.setServer(server);

        }}

 

 

上述代码中有个selectServe(),该方法是选择服务的进行负载均衡的方法,代码如下:

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

最终负载均衡交给loadBalancerContext来处理,

总结

总到来说,Feign的源码实现的过程如下:

  • 首先通过@EnableFeignCleints注解开启FeignCleint
  • 根据Feign的规则实现接口,并加@FeignCleint注解
  • 程序启动后,会进行包扫描,扫描所有的@ FeignCleint的注解的类,并将这些信息注入到ioc容器中。
  • 当接口的方法被调用,通过jdk的代理,来生成具体的RequesTemplate
  • RequesTemplate在生成Request
  • Request交给Client去处理,其中Client可以是HttpUrlConnection、HttpClient也可以是Okhttp
  • 最后Client被封装到LoadBalanceClient类,这个类结合类Ribbon做到了负载均衡。

  

  

 

posted @ 2018-09-03 14:32  陽66  阅读(1816)  评论(0编辑  收藏  举报