【Ribbon】 核心工作原理

Metadata

title: 【Ribbon】 核心工作原理
date: 2023-01-09 16:37
tags:
  - 行动阶段/完成
  - 主题场景/组件
  - 笔记空间/KnowladgeSpace/ProgramSpace/ModuleSpace
  - 细化主题/Module/Ribbon‘理论
categories:
  - Ribbon
keywords:
  - Ribbon
description: 【Ribbon】 核心工作原理

【Ribbon】 核心工作原理

接口 描述 默认实现
IClientConfig 定义Ribbon中管理配置的接口 DefaultClientConfigImpl
IRule 定义Ribbon中负载均衡策略的接口 ZoneAdvoidanceRule
IPing 定义定期Ping服务检查可用性的接口 DummyPing
ServerList<Server> 定义获取服务列表方法的接口 ConfigurationBasedServerList
ServerListFilter<Server> 定义特定期望获取服务列表方法的接口 ZonePreferenceServerListFilter
ILoadBalancer 定义负载均衡选择服务的核心方法的接口 ZoneAwareLoadBalancer
ServerListUpdater 为DynamicServerListLoadBalancer定义动态更新服务列表的接口 PollingServerListUpdater

源码解释

/**
 * Annotation to mark a RestTemplate or WebClient bean to be configured to use a
 * LoadBalancerClient.
 * @author Spencer Gibb
 */
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Qualifier
public @interface LoadBalanced {
}

在注释中可以看到:该注解标记在RestTemplate或者其他的WebClient的Bean上,来使用LoadBalancerClient。

LoadBalancerClient:该接口扩展自ServiceInstanceChooser

public interface LoadBalancerClient extends ServiceInstanceChooser {

    /**
     * Executes request using a ServiceInstance from the LoadBalancer for the specified
     * service.
     * @param serviceId The service ID to look up the LoadBalancer.
     * @param request Allows implementations to execute pre and post actions, such as
     * incrementing metrics.
     * @param <T> type of the response
     * @throws IOException in case of IO issues.
     * @return The result of the LoadBalancerRequest callback on the selected
     * ServiceInstance.
     */
    <T> T execute(String serviceId, LoadBalancerRequest<T> request) throws IOException;

    /**
     * Executes request using a ServiceInstance from the LoadBalancer for the specified
     * service.
     * @param serviceId The service ID to look up the LoadBalancer.
     * @param serviceInstance The service to execute the request to.
     * @param request Allows implementations to execute pre and post actions, such as
     * incrementing metrics.
     * @param <T> type of the response
     * @throws IOException in case of IO issues.
     * @return The result of the LoadBalancerRequest callback on the selected
     * ServiceInstance.
     */
    <T> T execute(String serviceId, ServiceInstance serviceInstance,
            LoadBalancerRequest<T> request) throws IOException;

    /**
     * Creates a proper URI with a real host and port for systems to utilize. Some systems
     * use a URI with the logical service name as the host, such as
     * http://myservice/path/to/service. This will replace the service name with the
     * host:port from the ServiceInstance.
     * @param instance service instance to reconstruct the URI
     * @param original A URI with the host as a logical service name.
     * @return A reconstructed URI.
     */
    URI reconstructURI(ServiceInstance instance, URI original);
}

ServiceInstanceChooser:

public interface ServiceInstanceChooser {

    /**
     * Chooses a ServiceInstance from the LoadBalancer for the specified service.
     * @param serviceId The service ID to look up the LoadBalancer.
     * @return A ServiceInstance that matches the serviceId.
     */
    ServiceInstance choose(String serviceId);
}
  • ServiceInstance choose(String serviceId):根据ServiceId,结合负载均衡器选择一个服务实例
  • <T> T execute(String serviceId, LoadBalancerRequest<T> request):使用来自LoadBalancer的ServiceInstance为指定的服务执行请求
  • <T> T execute(String serviceId, ServiceInstance serviceInstance,

LoadBalancerRequest<T> request):使用来自LoadBalancer的ServiceInstance为指定的服务执行请求,是上一个方法的重载,在实现类中可以看到它们的关系,就是前一个方法的细节实现、

  • URI reconstructURI(ServiceInstance instance, URI original):使用注解ip和port构建特定的URL以供Ribbon内部使用。Ribbon使用具有逻辑服务名称的URL作为host,例如:http://service-b/order/add。

从这些方法的功能可以知道这两个接口的重要性了。这两个接口的同一包下有一个类LoadBalancerAutoConfiguration。LoadBalancerAutoConfiguration在org.springframework.cloud.client.loadbalancer包下,在spring-cloud-commons里面。该自动配置类正式Ribbon的核心配置类。

  • LoadBalancerRequestFactory:用于创建LoadBalancerRequest给LoadBalancerInterceptor使用。
  • LoadBalancerInterceptorConfig:维护了LoadBalancerInterceptor与RestTemplateCustomizer的实例。
  • LoadBalancerInterceptor:拦截每一次的HTTP请求,将请求绑定金Ribbon的负载均衡的生命周期。
  • RestTemplateCustomizer:为每一个Restemplate绑定LoadBalancerInterceptor拦截器。
  • LoadBalancerInterceptor: 通过ClientHttpRequestInterceptor实现每次对HTTP请求的拦截,ClientHttpRequestInterceptor类是Spring中维护的请求拦截器,实现它的intercept方法就可以使得请求进入方法内,从而Ribbon就可以做一些自己的处理了。

核心类总结

在RibbonClientConfiguration中初始化了上面表格提到几个核心类

  • 初始化ribbonRule: ZoneAvoidanceRule
  • 初始化ribbonPing:DummyPing
  • 初始化ribbonServerList:ConfigurationBasedServerList
  • 初始化ServerListUpdater:new PollingServerListUpdater(config)
  • 初始化ILoadBalancer:ZoneAwareLoadBalancer
  • 初始化ribbonServerListFilter:ZonePreferenceServerListFilter
  • 初始化ribbonLoadBalancerContext:RibbonLoadBalancerContext
  • 初始化serverIntrospector:DefaultServerIntrospector