乐趣区

关于java: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);
            }

        };
    }
退出移动版