Ribbon LoadBalancerStat中定时统计服务提供者请求状态信息的源码分析

RibbonClientConfifiguration配置类中默认加载ZoneAwareLoadBalancer类看起

若不知道为啥从这个配置类的加载开始看起的话,我再补一篇从RestTemplate调用getForObject发起http请求开始看的好了

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

在初始化ZoneAwareLoadBalancer后会调用父类DynamicServerListLoadBalancer
在这里插入图片描述
在这里插入图片描述
进入restOfInit方法

void restOfInit(IClientConfig clientConfig) {
    boolean primeConnection = this.isEnablePrimingConnections();
    // turn this off to avoid duplicated asynchronous priming done in BaseLoadBalancer.setServerList()
    this.setEnablePrimingConnections(false);
    enableAndInitLearnNewServersFeature();

    updateListOfServers();
    if (primeConnection && this.getPrimeConnections() != null) {
        this.getPrimeConnections()
                .primeConnections(getReachableServers());
    }
    this.setEnablePrimingConnections(primeConnection);
    LOGGER.info("DynamicServerListLoadBalancer for client {} initialized: {}", clientConfig.getClientName(), this.toString());
}

其中的updateListOfServers();即步入定时统计服务提供者请求状态信息的任务的入口

@VisibleForTesting
public void updateListOfServers() {
    List<T> servers = new ArrayList<T>();
    if (serverListImpl != null) {
        servers = serverListImpl.getUpdatedListOfServers();
        LOGGER.debug("List of Servers for {} obtained from Discovery client: {}",
                getIdentifier(), servers);

        if (filter != null) {
            servers = filter.getFilteredListOfServers(servers);
            LOGGER.debug("Filtered List of Servers for {} obtained from Discovery client: {}",
                    getIdentifier(), servers);
        }
    }
    updateAllServerList(servers);
}

此方法最后会执行updateAllServerList(servers);1

之后进入父类BaseLoadBalancer的forceQuickPing()方法中执行启动runPinger()定时统计服务提供者请求状态信息的任务,这是初始化后强制执行更新的一次操作

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Ug4geI4J-1647352907552)(C:\Users\HASEE\AppData\Roaming\Typora\typora-user-images\image-20220315214648497.png)]

public void forceQuickPing() {
    if (canSkipPing()) {
        return;
    }
    logger.debug("LoadBalancer [{}]:  forceQuickPing invoking", name);
    
    try {
       new Pinger(pingStrategy).runPinger();
    } catch (Exception e) {
        logger.error("LoadBalancer [{}]: Error running forceQuickPing()", name, e);
    }
}
public void runPinger() throws Exception {
    if (!pingInProgress.compareAndSet(false, true)) { 
        return; // Ping in progress - nothing to do
    }
    
    // we are "in" - we get to Ping

    Server[] allServers = null;
    boolean[] results = null;

    Lock allLock = null;
    Lock upLock = null;

    try {
        /*
         * The readLock should be free unless an addServer operation is
         * going on...
         */
        allLock = allServerLock.readLock();
        allLock.lock();
        allServers = allServerList.toArray(new Server[allServerList.size()]);
        allLock.unlock();

        int numCandidates = allServers.length;
        results = pingerStrategy.pingServers(ping, allServers);

        final List<Server> newUpList = new ArrayList<Server>();
        final List<Server> changedServers = new ArrayList<Server>();

        for (int i = 0; i < numCandidates; i++) {
            boolean isAlive = results[i];
            Server svr = allServers[i];
            boolean oldIsAlive = svr.isAlive();

            svr.setAlive(isAlive);

            if (oldIsAlive != isAlive) {
                changedServers.add(svr);
                logger.debug("LoadBalancer [{}]:  Server [{}] status changed to {}", 
                  name, svr.getId(), (isAlive ? "ALIVE" : "DEAD"));
            }

            if (isAlive) {
                newUpList.add(svr);
            }
        }
        upLock = upServerLock.writeLock();
        upLock.lock();
        upServerList = newUpList;
        upLock.unlock();

        notifyServerStatusChangeListener(changedServers);
    } finally {
        pingInProgress.set(false);
    }
}

此外在BaseLoadBalancer类中有个属性

protected Timer lbTimer = null;

Timer由setupPingTask()方法实例化并启动加载定时任务

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kv7FGxPZ-1647352907553)(C:\Users\HASEE\AppData\Roaming\Typora\typora-user-images\image-20220315204936487.png)]

在new ShutdownEnabledTimer()的第二个参数即设置是否为守护进程,默认为true

之后设置定时任务中传入定时定时统计服务提供者请求状态信息的任务runPinger方法即定时执行并统计服务状态的更新

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3CpSn9rD-1647352907554)(C:\Users\HASEE\AppData\Roaming\Typora\typora-user-images\image-20220315205137109.png)]


  1. Update the AllServer list in the LoadBalancer if necessary and enable ↩︎

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Ribbon 可以通过配置来实现对每个服务提供者进行健康检查。具体步骤如下: 1. 首先,需要在服务提供者的配置文件添加健康检查的端点,例如在 Spring Boot 应用可以添加以下配置: ``` management.endpoints.web.exposure.include=health ``` 这样就会在服务提供者的 `/actuator/health` 端点暴露健康检查信息。 2. 在服务消费者的配置文件,需要添加 Ribbon 的健康检查配置,例如: ``` ribbon: eureka: enabled: true ServerListRefreshInterval: 2000 NIWSServerListClassName: com.netflix.loadbalancer.ConfigurationBasedServerList ServerListRefreshExecutorServiceClassName: com.netflix.loadbalancer.DefaultServerListRefreshExecutor PingInterval: 1000 connectTimeout: 2000 ReadTimeout: 5000 MaxAutoRetries: 1 MaxAutoRetriesNextServer: 2 OkToRetryOnAllOperations: true PrimeConnections: 100 EnablePrimeConnections: true listOfServers: localhost:8080,localhost:8081 ServerListRefreshFactoryClassName: com.netflix.loadbalancer.DefaultServerListRefreshFactory ServerListUpdaterClassName: com.netflix.loadbalancer.PollingServerListUpdater ServerListUpdaterPollingIntervalMs: 5000 # 配置 PingUrl,指定 Ribbon 用于检查服务健康状态的 URL NFLoadBalancerPingClassName: com.netflix.loadbalancer.PingUrl NFLoadBalancerPingUrl: http://${my.service.provider.ribbon.listOfServers}/actuator/health ``` 其,`NFLoadBalancerPingUrl` 属性指定了 Ribbon 用于检查服务健康状态的 URL,这里指定为服务提供者的 `/actuator/health` 端点。同时,`NFLoadBalancerPingClassName` 属性指定了 Ribbon 使用的 Ping 实现类,这里使用了默认的 `PingUrl`。 配置完成后,Ribbon 就会对服务提供者的健康状态进行定期检查,并且在服务不可用时将其从可用服务列表移除。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值