public class RoundRobinRule extends AbstractLoadBalancerRule {
private AtomicInteger nextServerCyclicCounter;
private static final boolean AVAILABLE_ONLY_SERVERS = true;
private static final boolean ALL_SERVERS = false;
private static Logger log = LoggerFactory.getLogger(RoundRobinRule.class);
//空参构造,设置nextServerCyclicCounter = 0
public RoundRobinRule() {
nextServerCyclicCounter = new AtomicInteger(0);
}
// 构造方法,设置AbstractLoadBalancerRule中的ILoadBalancer属性
public RoundRobinRule(ILoadBalancer lb) {
this();
setLoadBalancer(lb);
}
public Server choose(ILoadBalancer lb, Object key) {
if (lb == null) {
log.warn("no load balancer");
return null;
}
Server server = null;
int count = 0;
while (server == null && count++ < 10) {
//获取所有状态为up且可供连接的server
List<Server> reachableServers = lb.getReachableServers();
//获取所有的server列表
List<Server> allServers = lb.getAllServers();
//所有可供连接的server的数量
int upCount = reachableServers.size();
//所有的server数量
int serverCount = allServers.size();
if ((upCount == 0) || (serverCount == 0)) {
log.warn("No up servers available from load balancer: " + lb);
return null;
}
// nextServerIndex=1
int nextServerIndex = incrementAndGetModulo(serverCount);
// 从下标1的位置获取server
server = allServers.get(nextServerIndex);
if (server == null) {
// 线程让步,然后从头再来。哦,这该死的自我保护机制
Thread.yield();
continue;
}
// 如果该server是活的而且能提供服务,就返回该服务
if (server.isAlive() && (server.isReadyToServe())) {
return (server);
}
server = null;
}
// 重试10次后,心态崩溃并返回null
if (count >= 10) {
log.warn("No available alive servers after 10 tries from load balancer: "
+ lb);
}
return server;
}
private int incrementAndGetModulo(int modulo) {
//modulo为所有server数量
for (;;) {
//nextServerCyclicCounter是个AtomicInteger类,初始值为0
int current = nextServerCyclicCounter.get(); // current=0
//只要modulo>1,那么next=1
int next = (current + 1) % modulo;
//如果current=next,就以原子方式将current设置为next,并返回next
if (nextServerCyclicCounter.compareAndSet(current, next))
return next;
}
}
/**
*此方法为native方法:读取传入对象AtomicInteger在内存中偏移量为valueOffset位置的值与期望值expect作比较。
*相等就把update值赋值给offset位置的值。方法返回true。
*不相等,就取消赋值,方法返回false。
*CAS思想:比较并交换。
*即,以原子方式将值设置为给定的更新值,保证无锁并发的安全性。
*/
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
@Override
public Server choose(Object key) {
return choose(getLoadBalancer(), key);
}
@Override
public void initWithNiwsConfig(IClientConfig clientConfig) {
}
}
Spring Cloud Ribbon's default strategy RoundRobinRule source code comments
Guess you like
Origin blog.csdn.net/single_0910/article/details/112696676
Recommended
Ranking