标签:abstract for 随机 override rri ble ace run netflix
/**
* Interface that defines a "Rule" for a LoadBalancer. A Rule can be thought of
* as a Strategy for loadbalacing. Well known loadbalancing strategies include
* Round Robin, Response Time based etc.
*
* @author stonse
*
*/
public interface IRule{
/*
* choose one alive server from lb.allServers or
* lb.upServers according to key
*
* @return choosen Server object. NULL is returned if none
* server is available
*/
public Server choose(Object key);
public void setLoadBalancer(ILoadBalancer lb);
public ILoadBalancer getLoadBalancer();
}
AvailabilityFilteringRule: 先过滤掉跳闸,访问故障的服务,再对剩下的服务进行轮询
RoundRobinRule:轮询调度,默认的
RandomRule:随机调度
WeightedResponseTimeRule:根据权重调度
RetryRule:会先轮询获取服务,如果获取失败,则会在一定的时间内进行重试
@SpringBootApplication
@EnableEurekaClient //为Eureka客户端
//微服务启动时就会去加载我们的Ribbon配置类
@RibbonClient(name = "provider-person-8001",configuration = NumberRule.class)
public class PersonConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(PersonConsumerApplication.class,args);
}
}
@Configuration
public class ZZNumberConfig {
@Bean
public NumberRule numberRule(){
return new NumberRule();
}
}
public class NumberRule extends AbstractLoadBalancerRule {
private static Logger log = LoggerFactory.getLogger(RoundRobinRule.class);
private int total = 0;//总数
private int cunnentIndex = 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 < 3){
server = reachableServers.get(cunnentIndex);
total++;
}else {
total =0;
cunnentIndex++;
if(cunnentIndex >= reachableServers.size()){
cunnentIndex = 0;
}
server = reachableServers.get(cunnentIndex);
}
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) {
}
}
标签:abstract for 随机 override rri ble ace run netflix
原文地址:https://www.cnblogs.com/xiaominaaaa/p/14259080.html