微服务之Ribbon原理解析

Ribbon原理解析

1.引言

什么是Ribbon

  • Ribbon是Netflix公司的一个负载均衡项目,可以在进行服务调用时做负载均衡;

2.Ribbon基本使用

Ribbon结合Http

  • Ribbon通常和Http请求结合,对Http请求进行负载均衡;最简单的使用如下,通过注入RestTemplate,并且打上@LoadBlanced注解,即可得到一个带有负载均衡效果的RestTemplate
@Configuration
public class HttpConfiguration {
    @Bean
    @LoadBalanced
    public RestTempttpTlate restTemplate() {
        return new RestTemplate();
    }
}
  • 使用时,只需要把RestTemplate发送请求时的URL中的主机名host替换为服务提供方的名字;那么在调用时,就会自动进行负载均衡
@RestController
public class TestController {
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/test")
    public String test() {
        //HelloServiceProvider为服务提供方名称
        return restTemplate.getForEntity("http://HelloServiceProvider/hello?info=okkk", String.class).getBody();
    }
}
  • 当然,这里还有配置好注册中心,将服务提供方和消费方都注册到注册中心上

3.Ribbon和RestTemplate整合原理

原理概述

  • RestTemplate相信大家都有用过,相当于一个发送Http请求的工具;但是为何引入@LoadBlanced就可以实现负载均衡了呢?
  • 简单来说:
    • RestTemplate在发送请求过程中,会构造一条具有多个拦截器的执行链
    • Ribbon可以借助拦截器,在RestTemplate中加入一个LoadBalancerInterceptor拦截器;
    • 这样在发送请求时,请求经过拦截器,Ribbon就可以根据请求的URL中的主机名(即服务名, 下面的HelloServiceProvider),去注册中心拿到提供该服务的所有主机
    • 并且根据负载均衡策略,选择其中一个,然后把服务名替换为真正的IP,接着继续执行下一个拦截器,最终发送请求
//restTempalte负载均衡发送请求示例,其中HelloServiceProvider为服务名,需要被替换为真实IP地址
restTemplate.getForEntity("http://HelloServiceProvider/hello?info=okkk", String.class).getBody();

源码解析

  • Spring的IOC容器在刷新过程中,会执行到如下过程;该过程是bean容器刷新比较后面的一步,这是大部分单例bean都已经实例化完成;会遍历所有实现了SmartInitializingSingleton接口的bean,并调用它的afterSingletonsInstantiated方法
//DefaultListableBeanFactory#preInstantiateSingletons部分代码

for (String beanName : beanNames) {
    Object singletonInstance = getSingleton(beanName);
    if (singletonInstance instanceof SmartInitializingSingleton) {
        final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                smartSingleton.afterSingletonsInstantiated();
                return null;
            }, getAccessControlContext());
        }
        else {
            //调用afterSingletonsInstantiated方法
            smartSingleton.afterSingletonsInstantiated();
        }
    }
}
  • LoadBalancerAutoConfiguration类:SpringCloud中的一个自动配置类,负责负载均衡方面的配置,会向容器中注入如下几个Bean对象(截取部分源码); 其中第一个是SmartInitializingSingleton类型的对象,也就是上面所说的接口;所以它的方法会在上面的过程中被调用;具体方法内容看下面注释;(下面这两个Bean对象都是lambda表达式的形式,注意别看混了)
//LoadBalancerAutoConfiguration

public class LoadBalancerAutoConfiguration {
    
    @Bean //参数传入的是restTemplateCustomizers,这个应该是有ApplicationContext进行注入所有的customizer
    public SmartInitializingSingleton loadBalancedRestTemplateInitializerDeprecated(
        final ObjectProvider<List<RestTemplateCustomizer>> restTemplateCustomizers) {
        return () -> restTemplateCustomizers.ifAvailable(customizers -> {
            //遍历所有RestTemplate对象
            for (RestTemplate restTemplate : LoadBalancerAutoConfiguration.this.restTemplates) {
                for (RestTemplateCustomizer customizer : customizers) {
                    //调用customizer#customize方法,对restTemplate做一些操作,具体看下面的Bean
                    customizer.customize(restTemplate);
                }
            }
        });
    }

    //注入customizer对象
    @Bean
    @ConditionalOnMissingBean
    public RestTemplateCustomizer restTemplateCustomizer(
        final LoadBalancerInterceptor loadBalancerInterceptor) {
        return restTemplate -> {
            //这就是上面的Bean执行customize方法,拿到该restTemplate所有拦截器
            List<ClientHttpRequestInterceptor> list = new ArrayList<>(
                restTemplate.getInterceptors());
            //加入负载均衡拦截器
            list.add(loadBalancerInterceptor);
            //重新设置拦截器给restTemplate
            restTemplate.setInterceptors(list);
        };
    }
}
  • 通过上面的步骤,restTemplate中就会被注入了LoadBalancerInterceptor拦截器;发送http请求时会经过拦截器,就可以将URL的服务名替换为负载均衡过后的真正IP地址了

4.负载均衡流程

核心类

  • LoadBalanceClient:上面说到Http请求发送时,会经过Ribbon的LoadBalancerInterceptor拦截器进行负载均衡,该拦截器会把请求交给LoadBalancerClient进行负载均衡;该类是负载均衡客户端,也可以看成负载均衡的入口;采用的实现类是RibbonLoadBalancerClient,看一下继承图

在这里插入图片描述

  • ILoadBalancerRibbonLoadBalancerClient内部的execute方法会以Http请求的服务名为key,找到ILoadBalancer对象,这个ILoadBalancer就是专门负责这个服务的负载均衡;继承图如下
    • DynamicServerListLoadBalance: 具有ServerList功能的ILoadBalance,ServerList后面会讲,它能够维护和更新本服务对应的所有主机信息
    • ZoneAwareLoadBalance: 该类是DynamicServerListLoadBalancer的子类,具有区域感知(ZoneAware)功能,它可以把所有主机根据请求状况进行区域划分,当主机请求超时时,它会把相关主机从活跃区域踢出,避免影响服务质量;详情可看类上的注释
/**
 * Load balancer that can avoid a zone as a whole when choosing server. 
 *<p>
 * The key metric used to measure the zone condition is Average Active Requests,
which is aggregated per rest client per zone. It is the
total outstanding requests in a zone divided by number of available targeted instances (excluding circuit breaker tripped instances).
This metric is very effective when timeout occurs slowly on a bad zone.
<p>
The  LoadBalancer will calculate and examine zone stats of all available zones. If the Average Active Requests for any zone has reached a configured threshold, this zone will be dropped from the active server list. In case more than one zone has reached the threshold, the zone with the most active requests per server will be dropped.
Once the the worst zone is dropped, a zone will be chosen among the rest with the probability proportional to its number of instances.
A server will be returned from the chosen zone with a given Rule (A Rule is a load balancing strategy, for example {@link AvailabilityFilteringRule})
For each request, the steps above will be repeated. That is to say, each zone related load balancing decisions are made at real time with the up-to-date statistics aiding the choice.
 */

在这里插入图片描述

  • IRule:代表负载均衡策略,ILoadBalancer的负载均衡由它进行处理,Ribbon内置了多种负载均衡策略,都实现了该接口

在这里插入图片描述

源码流程

  • 前面说了负载均衡入口是RestTemplate拦截器,所以看一下LoadBalancerInterceptor的intercept方法
//LoadBalancerInterceptor#intercept
@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);
    //拿到loadBalancer,它是一个LoadBalancerClient类型对象,并调用execute方法
    return this.loadBalancer.execute(serviceName,
                                     this.requestFactory.createRequest(request, body, execution));
}
  • 上述LoadBalancerClient实际用的实现类是RibbonLoadBalancerClient,先看一下其父接口LoadBalancerClient的方法
public interface LoadBalancerClient extends ServiceInstanceChooser {
    //用于执行http负载均衡请求
	<T> T execute(String serviceId, LoadBalancerRequest<T> request) throws IOException;

	<T> T execute(String serviceId, ServiceInstance serviceInstance,
			LoadBalancerRequest<T> request) throws IOException;
    //重构URI,替换服务名
	URI reconstructURI(ServiceInstance instance, URI original);

}
  • RibbonLoadBalancerClient的execute方法如下
//RibbonLoadBalancerClient#execute
public <T> T execute(String serviceId, LoadBalancerRequest<T> request, Object hint)
    throws IOException {
    //根据serviceId拿到ILoadBalancer,交由它进行负载均衡
    ILoadBalancer loadBalancer = getLoadBalancer(serviceId);
    //根据loadBalancer拿到真正的服务提供者
    Server server = getServer(loadBalancer, hint);
    if (server == null) {
        throw new IllegalStateException("No instances available for " + serviceId);
    }
    //包装Server
    RibbonServer ribbonServer = new RibbonServer(serviceId, server,
                                                 isSecure(server, serviceId),
                                                 serverIntrospector(serviceId).getMetadata(server));

    //执行请求
    return execute(serviceId, ribbonServer, request);
}

//RibbonLoadBalancerClient#getLoadBalancer
protected ILoadBalancer getLoadBalancer(String serviceId) {
	//从clientFactory中获得该服务对应的ILoadBalancer	
    return this.clientFactory.getLoadBalancer(serviceId);
}
  • 这里ILoadBalancer loadBalancer = getLoadBalancer(serviceId)这句代码是重点,它会根据当前URL中的serviceId,先从工厂中拿到对应的ApplicationContext(首次取没有则新建容器并refresh),接着再从IOC容器中拿到ILoadBalancer类型的bean;由于调用栈比较复杂,下面只摘取部分重点
protected ILoadBalancer getLoadBalancer(String serviceId) {
    //从SpringClientFactory工厂中获取该serviceId对应的ILoadBalancer
    return this.clientFactory.getLoadBalancer(serviceId);
}

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

public <T> T getInstance(String name, Class<T> type) {
    //获取服务名对应的ApplicationContext
    AnnotationConfigApplicationContext context = getContext(name);
    if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context,
                                                            type).length > 0) {
        //从ApplicationContext中后去ILoadBalancer类型的bean
        return context.getBean(type);
    }
    return null;
}

protected AnnotationConfigApplicationContext getContext(String name) {
    //大致逻辑就是直接容map中拿,没有则创建一个并缓存
    if (!this.contexts.containsKey(name)) {
        synchronized (this.contexts) {
            if (!this.contexts.containsKey(name)) {
                this.contexts.put(name, createContext(name));
            }
        }
    }
    return this.contexts.get(name);
}
  • 因此可以看出,Ribbon中,每个服务会对应一个ApplicationContext,内部维护了各种bean信息,包括负责负载均衡的ILoadBalancer;每个ApplicationContext内部都有自己的ILoadBalancer
  • getServer()方法最终会调用ILoadBalancer的chooseServer方法,代码如下
//BaseLoadBalancer#chooseServer
public Server chooseServer(Object key) {
    if (counter == null) {
        counter = createCounter();
    }
    counter.increment();
    //如果没有配置rule则返回
    if (rule == null) {
        return null;
    } else {
        try {
            //由rule执行真正的负载均衡
            return rule.choose(key);
        } catch (Exception e) {
            logger.warn("LoadBalancer [{}]:  Error choosing server for key {}", name, key, e);
            return null;
        }
    }
}
  • 下面以RandomRule为例看一下choose方法,篇幅原因只保留部分代码,详情可自己debug
//RandomRule#choose
public Server choose(ILoadBalancer lb, Object key) {
    if (lb == null) {
        return null;
    }
    Server server = null;

    while (server == null) {
        //... 从ILoadBalancer中拿到该服务对应的所有Server
        List<Server> upList = lb.getReachableServers();
        List<Server> allList = lb.getAllServers();
		//... 产生随机数,并拿到对应Server
        int index = chooseRandomInt(serverCount);
        server = upList.get(index);
		//...

        if (server.isAlive()) {
            return (server);
        }
		//...
    }
    return server;
}

小结

  • 这样就完成了负载均衡过程,梳理一下大致流程
    • Http请求经过LoadBalancerInterceptor拦截器,它将调用LoadBalancerClient进行处理
    • LoadBalancerClient(实现类Ribbon``LoadBalancerClient)根据服务名拿到对应的ApplicationContext,并从容器中拿到ILoadBalancer(实际类ZoneAwareLoadBalancer
    • ILoadBalancer中获取服务提供者Server,具体是调用chooseServer方法,内部会使用IRule进行负载均衡,并返回合适的Server
    • IRule才是真正的负载均衡实现接口,Ribbon内置多种默认负载均衡策略
  • 以上流程讲述了从RestTemplate与Ribbon整合,到一次请求发起实现负载均衡的大致流程;但是还不涉及Ribbon如何维护注册中心中的服务及对应的主机列表操作;即Ribbon需要定时获取注册中心的服务信息,供负载均衡使用

5.服务列表拉取和刷新

核心类

  • ServerList:该接口用于表示向注册中心拉取服务信息
public interface ServerList<T extends Server> {
    public List<T> getInitialListOfServers();
    
    public List<T> getUpdatedListOfServers();   
}

源码流程

  • 前面说到过,每个服务都有自己的ILoadBalancer(默认是ZoneAwareLoadBalancer),其父类为DynamicServerListLoadBalancer,它会负责服务对应的主机列表信息;
  • DynamicServerListLoadBalancer在创建过程中,会调用如下方法进行服务列表初始化
public DynamicServerListLoadBalancer(IClientConfig clientConfig, IRule rule, IPing ping,
                                     ServerList<T> serverList, ServerListFilter<T> filter,
                                     ServerListUpdater serverListUpdater) {
    super(clientConfig, rule, ping);
    this.serverListImpl = serverList;
    this.filter = filter;
    this.serverListUpdater = serverListUpdater;
    if (filter instanceof AbstractServerListFilter) {
        ((AbstractServerListFilter) filter).setLoadBalancerStats(getLoadBalancerStats());
    }
    //调用该方法进行主机列表初始化
    restOfInit(clientConfig);
}

void restOfInit(IClientConfig clientConfig) {
    //...
    updateListOfServers();
    //...
}

//这是另一个构造方法,可能是使用自定义配置时
public DynamicServerListLoadBalancer(IClientConfig clientConfig) {
    initWithNiwsConfig(clientConfig);
}
    
//DynamicServerListLoadBalancer#initWithNiwsConfig
public void initWithNiwsConfig(IClientConfig clientConfig) {
    try {
        super.initWithNiwsConfig(clientConfig);
        //从配置文件中拿到NIWSServerListClassName对应的值,应该是拿到配置的ServerList实现类,负责维护服务信息
        //当注册中心不同时,应该可以动态替换
        String niwsServerListClassName = clientConfig.getPropertyAsString(
            CommonClientConfigKey.NIWSServerListClassName,
            DefaultClientConfigImpl.DEFAULT_SEVER_LIST_CLASS);
		//实例化ServerList
        ServerList<T> niwsServerListImpl = (ServerList<T>) ClientFactory
            .instantiateInstanceWithClientConfig(niwsServerListClassName, clientConfig);
        //保存
        this.serverListImpl = niwsServerListImpl;
		//...
		//拿到ServerListUpdaterClassName配置的类
        String serverListUpdaterClassName = clientConfig.getPropertyAsString(
            CommonClientConfigKey.ServerListUpdaterClassName,
            DefaultClientConfigImpl.DEFAULT_SERVER_LIST_UPDATER_CLASS
        );
		//实例化
        this.serverListUpdater = (ServerListUpdater) ClientFactory
            .instantiateInstanceWithClientConfig(serverListUpdaterClassName, clientConfig);
		//在该函数中,会进行服务初始化
        restOfInit(clientConfig);
    } catch (Exception e) {
        throw new RuntimeException(
            "Exception while initializing NIWSDiscoveryLoadBalancer:"
            + clientConfig.getClientName()
            + ", niwsClientConfig:" + clientConfig, e);
    }
}
  • 接下来调用DynamicServerListLoadBalancer#restOfInit方法,最终会调用updateListOfServers方法进行列表更新
@VisibleForTesting
public void updateListOfServers() {
    List<T> servers = new ArrayList<T>();
    //判断serverListImpl是否有配置
    if (serverListImpl != null) {
        //拉取所有的Servers
        servers = serverListImpl.getUpdatedListOfServers();
        LOGGER.debug("List of Servers for {} obtained from Discovery client: {}",
                     getIdentifier(), servers);
		//如果由过滤规则,对Server进行过滤
        if (filter != null) {
            servers = filter.getFilteredListOfServers(servers);
            LOGGER.debug("Filtered List of Servers for {} obtained from Discovery client: {}",
                         getIdentifier(), servers);
        }
    }
    //更新本地的ServerList
    updateAllServerList(servers);
}

@Override
public List<DiscoveryEnabledServer> getUpdatedListOfServers() {
    List<DiscoveryEnabledServer> servers = setZones(
        this.list.getUpdatedListOfServers());	//这里才是真正获取主机的方法, list是一个ServerList类型的变量,根据注册中心不同,具体实现不同
    return servers;
}
  • 如果注册中心使用Eureka,那么ServerList使用的是DiscoveryEnabledNIWSServerList,如果是其他注册中心,可以替换,下面看一下它的getUpdatedListOfServers方法,层层调用后进入如下方法,篇幅原因省略部分代码
//DiscoveryEnabledNIWSServerList#obtainServersViaDiscovery
private List<DiscoveryEnabledServer> obtainServersViaDiscovery() {
    List<DiscoveryEnabledServer> serverList = new ArrayList<DiscoveryEnabledServer>();
	//...
	//拿到Eureka客户端,它可以进行服务拉取,注册等
    EurekaClient eurekaClient = eurekaClientProvider.get();
    if (vipAddresses!=null){
        for (String vipAddress : vipAddresses.split(",")) {
            // if targetRegion is null, it will be interpreted as the same region of client
            List<InstanceInfo> listOfInstanceInfo = eurekaClient.getInstancesByVipAddress(vipAddress, isSecure, targetRegion);
            for (InstanceInfo ii : listOfInstanceInfo) {
                if (ii.getStatus().equals(InstanceStatus.UP)) {
					//... 封装服务并保存
                    DiscoveryEnabledServer des = createServer(ii, isSecure, shouldUseIpAddr);
                    serverList.add(des);
                }
            }
            if (serverList.size()>0 && prioritizeVipAddressBasedServers){
                break; // if the current vipAddress has servers, we dont use subsequent vipAddress based servers
            }
        }
    }
    return serverList;
}

6.服务列表更新

  • Ribbon服务列表更新是通过定时任务来完成的;相关类是PollingServerListUpdater;可以看一下它的start方法
public synchronized void start(final UpdateAction updateAction) {
    if (isActive.compareAndSet(false, true)) {
        //创建定时任务
        final Runnable wrapperRunnable = new Runnable() {
            @Override
            public void run() {
                //...
                try {
                    //更新主机信息
                    updateAction.doUpdate();
                    lastUpdated = System.currentTimeMillis();
                } catch (Exception e) {
                    logger.warn("Failed one update cycle", e);
                }
            }
        };
		//设置定时任务
        scheduledFuture = getRefreshExecutor().scheduleWithFixedDelay(
            wrapperRunnable,
            initialDelayMs,
            refreshIntervalMs,
            TimeUnit.MILLISECONDS
        );
    }
}
  • 另外,Ribbon还会定期去Ping每一个主机,保证主机存活

7.服务注册中心

  • Ribbon默认的服务注册中心是eureka,如果想用nacos做服务注册中心,可以直接添加nacos依赖即可;
  • nacos中包含了Ribbon,并且提供了NacosServerList来与注册中心进行信息拉取
  • 而Eureka中使用的是DiscoveryEnabledNIWSServerList
  • 以上纯属猜测,具体需要自己实践一下;但Ribbon的注册中心替换原理应该类似,通过提供ServerList来实现
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值