com.region.loadbalancer.policy.RoundRobinPolicy Maven / Gradle / Ivy
package com.region.loadbalancer.policy;
import com.region.loadbalancer.group.Server;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Polling Scheduling Policy
*
* @author liujieyu
* @date 2023/5/25 23:49
* @desciption
*/
public class RoundRobinPolicy implements BalancerPolicy{
AtomicInteger count = new AtomicInteger(0);
@Override
public Server choose(List servers) {
if (servers == null || servers.isEmpty()) {
return null;
}
if (servers.size() == 1) {
return servers.get(0);
}
if (count.get() >= Integer.MAX_VALUE && (count.getAndIncrement() & (servers.size() - 1)) == 0) {
count.set(0);
}
return servers.get(count.getAndIncrement() & (servers.size() - 1));
}
}