理解负载均衡之随机策略RandomRule

学习Ribbon时学到了负载均衡的策略,老师讲解了随机策略的源码。感觉挺简单的,可以照猫画虎自定义负载均衡策略。就简单记下,好记性不如烂笔头。
自定义负载均衡策略时都需要继承AbstractLoadBalancerRule

package com.netflix.loadbalancer;
import com.netflix.client.config.IClientConfig;
import edu.umd.cs.findbugs.annotations.SuppressWarnings;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
//
public class RandomRule extends AbstractLoadBalancerRule {
    public RandomRule() {
    }

    @SuppressWarnings({"RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"})
    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        } else {
            Server server = null;

            while(server == null) {
                if (Thread.interrupted()) {  //如果线程中断就返回null
                    return null;
                }

                List<Server> upList = lb.getReachableServers();//获取活着的服务
                List<Server> allList = lb.getAllServers();//获取所有的服务
                int serverCount = allList.size();
                if (serverCount == 0) {
                    return null;
                }

                int index = this.chooseRandomInt(serverCount);//产生0-serverCount之间的随机数
                server = (Server)upList.get(index); //随机获取服务
                if (server == null) {  //如果当前服务是null就让出时间片
                    Thread.yield();
                } else {
                    if (server.isAlive()) { //如果当前服务是活着的就返回
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }

            return server;
        }
    }

    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }

    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}

你可能感兴趣的:(笔记,java,ribbon,分布式)