需求:每台机器访问五次后轮询到下一台机器
背景:三台eureka注册中心,三台服务提供者,一台服务消费者
接上篇文章,一些注意事项已经在上篇里提到了,本篇主讲如何修改算法
步骤
.首先继承AbstractLoadBalancerRule
.其次可以将RoundRobinRule中的代码拷贝过来,基于轮询的基础上进行修改
package com.custom.rule;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.RoundRobinRule;
import com.netflix.loadbalancer.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class RoundRobinRule_ltt extends AbstractLoadBalancerRule {
private AtomicInteger total;
private AtomicInteger current;
private static Logger log = LoggerFactory.getLogger(RoundRobinRule_ltt.class);
public RoundRobinRule_ltt() {
total = new AtomicInteger(0);
current = new AtomicInteger(0);
}
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) {
List<Server> reachableServers = lb.getReachableServers();
List<Server> allServers = lb.getAllServers();
int upCount = reachableServers.size();
int serverCount = allServers.size();
if ((upCount == 0) || (serverCount == 0)) {
log.warn("No up servers available from load balancer: " + lb);
return null;
}
if(total.intValue()<5){
total.incrementAndGet();
server = allServers.get(current.get());
}else{
total = new AtomicInteger(0);
current.incrementAndGet();
if (current.get()>=serverCount){
current.set(0);
}
}
if (server == null) {
/* Transient. */
Thread.yield();
continue;
}
if (server.isAlive() && (server.isReadyToServe())) {
return (server);
}
// Next.
server = null;
}
if (count >= 10) {
log.warn("No available alive servers after 10 tries from load balancer: "
+ lb);
}
return server;
}
@Override
public Server choose(Object key) {
return choose(getLoadBalancer(), key);
}
@Override
public void initWithNiwsConfig(IClientConfig clientConfig) {
}
}
网友评论