SpringCloud Ribbon 部分源码

Posted 熙熙

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringCloud Ribbon 部分源码相关的知识,希望对你有一定的参考价值。

1:ribbon是提供通过serviceId访问服务的能力,而且提供了负载均衡能力。在springcloud里面,有2个自动配置加载类 LoadBalancerAutoConfiguration 和 RibbonAutoConfiguration。LoadBalancerAutoConfiguration主要完成对 RestTemplate 对象的负载均衡访问,RibbonAutoConfiguration主要是对Ribbon所需组件的实例化。分别在springcloud-common 和 netflix-core 的 spring.foctories 文件里。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=
org.springframework.cloud.netflix.hystrix.HystrixAutoConfiguration,
org.springframework.cloud.netflix.hystrix.security.HystrixSecurityAutoConfiguration,
org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration,
org.springframework.cloud.netflix.rx.RxJavaAutoConfiguration,

org.springframework.boot.autoconfigure.EnableAutoConfiguration=
org.springframework.cloud.client.CommonsClientAutoConfiguration,
org.springframework.cloud.client.loadbalancer.LoadBalancerAutoConfiguration,
org.springframework.cloud.client.serviceregistry.ServiceRegistryAutoConfiguration, 

2:RibbonAutoConfiguration 主要是对Ribbon组件的实例化,其对应关系是:
IClientConfig --> DefaultClientConfigImpl
IRule --> ZoneAvoidanceRule
IPing --> DummyPing
ServerList --> ConfigurationBasedServerList
ServerListUpdater --> PollingServerListUpdater
ILoadBalancer --> ZoneAwareLoadBalancer
LoadBalancerClient --> RibbonLoadBalancerClient
同时,也会创建:SpringClientFactory 对象。

3:LoadBalancerAutoConfiguration 主要是对 RestTemplate 进行负载均衡配置。 其主要实现是创建拦截器 LoadBalancerInterceptor。然后对 RestTemplate 进行自定义配置,代码如下:

@Bean
    public SmartInitializingSingleton loadBalancedRestTemplateInitializer(
            final List<RestTemplateCustomizer> customizers) {
        return new SmartInitializingSingleton() {
            @Override
            public void afterSingletonsInstantiated() {
                for (RestTemplate restTemplate : LoadBalancerAutoConfiguration.this.restTemplates) {
                    for (RestTemplateCustomizer customizer : customizers) {
                        customizer.customize(restTemplate);
                    }
                }
            }
        };
    }
@Configuration
    @ConditionalOnMissingClass("org.springframework.retry.support.RetryTemplate")
    static class LoadBalancerInterceptorConfig {
        @Bean
        public LoadBalancerInterceptor ribbonInterceptor(
                LoadBalancerClient loadBalancerClient,
                LoadBalancerRequestFactory requestFactory) {
            return new LoadBalancerInterceptor(loadBalancerClient, requestFactory);
        }

        @Bean
        @ConditionalOnMissingBean
        public RestTemplateCustomizer restTemplateCustomizer(
                final LoadBalancerInterceptor loadBalancerInterceptor) {
            return new RestTemplateCustomizer() {
                @Override
                public void customize(RestTemplate restTemplate) {
                    List<ClientHttpRequestInterceptor> list = new ArrayList<>(
                            restTemplate.getInterceptors());
                    list.add(loadBalancerInterceptor);
                    restTemplate.setInterceptors(list);
                }
            };
        }
    } 

在上面的代码中,增加的拦截器类是:LoadBalancerInterceptor。 LoadBalancerClient 接口的实现类是:RibbonLoadBalancerClient。

4:在使用 RestTemplate 进行 POST, GET 请求的时候,最终执行的是 方法:LoadBalancerInterceptor#intercept。 在该方法里,调用方法:RibbonLoadBalancerClient#execute(String, LoadBalancerRequest<T>)

@Override
    public ClientHttpResponse intercept(final HttpRequest request, final byte[] body,
            final ClientHttpRequestExecution execution) throws IOException {
        final URI originalUri = request.getURI();
        String serviceName = originalUri.getHost();
        Assert.state(serviceName != null, "Request URI does not contain a valid hostname: " + originalUri);
        return this.loadBalancer.execute(serviceName, requestFactory.createRequest(request, body, execution));
    } 

5:在 execute 方法里,主要是 获取到负载均衡器,获取服务提供者的访问路径,访问

@Override
    public <T> T execute(String serviceId, LoadBalancerRequest<T> request) throws IOException {
        ILoadBalancer loadBalancer = getLoadBalancer(serviceId);  //获取负载均衡器
        Server server = getServer(loadBalancer);  //获取服务访问路径,包括IP端口
        if (server == null) {
            throw new IllegalStateException("No instances available for " + serviceId);
        }
        RibbonServer ribbonServer = new RibbonServer(serviceId, server, isSecure(server,
                serviceId), serverIntrospector(serviceId).getMetadata(server));

        return execute(serviceId, ribbonServer, request); //访问服务
    } 

6:在 SpringClientFactory#getLoadBalancer 里,获取的是接口 ILoadBalancer 的实例。其实现是 构造Spring的上下文对象 AnnotationConfigApplicationContext, 然后加载配置类:RibbonClientConfiguration.
在RibbonClientConfiguration类里,会实例化 ZoneAwareLoadBalancer 对象。获取到 ILoadBalancer 的单例模式后,会缓存在内存里面。

public ILoadBalancer getLoadBalancer(String name) {
        return getInstance(name, ILoadBalancer.class);
    }

protected AnnotationConfigApplicationContext getContext(String name) {
        if (!this.contexts.containsKey(name)) {
            synchronized (this.contexts) {
                if (!this.contexts.containsKey(name)) {
                    this.contexts.put(name, createContext(name));
                }
            }
        }
        return this.contexts.get(name);
    }

@Bean
    @ConditionalOnMissingBean
    public ILoadBalancer ribbonLoadBalancer(IClientConfig config,
            ServerList<Server> serverList, ServerListFilter<Server> serverListFilter,
            IRule rule, IPing ping, ServerListUpdater serverListUpdater) {
        if (this.propertiesFactory.isSet(ILoadBalancer.class, name)) {
            return this.propertiesFactory.get(ILoadBalancer.class, config, name);
        }
        return new ZoneAwareLoadBalancer<>(config, rule, ping, serverList,
                serverListFilter, serverListUpdater);
    } 

7:ZoneAwareLoadBalancer 会调用 ZoneAvoidanceRule 里的 choose() 方法。 该方法里面,通过负载均衡器里,获取所有的服务节点(IRule实例里的负载均衡器是在ZoneAwareLoadBalancer 实例化的时候设置的)。lb.getAllServers() 方法获取的是获取的缓存对象 allServerList。

@Override
    public Server choose(Object key) {
        ILoadBalancer lb = getLoadBalancer();
        Optional<Server> server = getPredicate().chooseRoundRobinAfterFiltering(lb.getAllServers(), key);
        if (server.isPresent()) {
            return server.get();
        } else {
            return null;
        }       
    } 

8:获取到服务列表后,ZoneAvoidanceRule 后面 使用 chooseRoundRobinAfterFiltering() 选择服务,依照代码,使用的是循环算法选择 Server

public Optional<Server> chooseRoundRobinAfterFiltering(List<Server> servers, Object loadBalancerKey) {
        List<Server> eligible = getEligibleServers(servers, loadBalancerKey);
        if (eligible.size() == 0) {
            return Optional.absent();
        }
        return Optional.of(eligible.get(nextIndex.getAndIncrement() % eligible.size()));
    } 

9:选定Server对象后,里面有访问的实例的IP和端口信息。会使用 httpClient 对象访问对象的节点。代码如下:

public LoadBalancerRequest<ClientHttpResponse> createRequest(final HttpRequest request,
            final byte[] body, final ClientHttpRequestExecution execution) {
        return new LoadBalancerRequest<ClientHttpResponse>() {
            @Override
            public ClientHttpResponse apply(final ServiceInstance instance)
                    throws Exception {
                HttpRequest serviceRequest = new ServiceRequestWrapper(request, instance, loadBalancer);
                if (transformers != null) {
                    for (LoadBalancerRequestTransformer transformer : transformers) {
                        serviceRequest = transformer.transformRequest(serviceRequest, instance);
                    }
                }
                return execution.execute(serviceRequest, body);
            }

        };
    }

以上是关于SpringCloud Ribbon 部分源码的主要内容,如果未能解决你的问题,请参考以下文章

SpringCloud-创建服务消费者-Ribbon方式(附代码下载)

SpringCloud---Ribbon服务调用,源码分析

SpringCloud----Ribbon服务调用,源码分析

SpringCloud集成Ribbon

SpringCloud系列之三---Ribbon负载均衡使用

SpringCloud之Ribbon进行服务调用