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 ↩︎

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值