All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.fashionbrot.ribbon.rule.RandomRule Maven / Gradle / Ivy

Go to download

mars-ribbon-api 负载均衡工具 https://github.com/fashionbrot/mars-dynamic-config

There is a newer version: 0.1.3
Show newest version
package com.github.fashionbrot.ribbon.rule;

import com.github.fashionbrot.ribbon.AbstractLoadBalancerRule;
import com.github.fashionbrot.ribbon.loadbalancer.ILoadBalancer;
import com.github.fashionbrot.ribbon.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Random;

/**
 * @author fashionbrot
 * @version 0.1.0
 * @date 2019/12/8 22:45
 */
@Slf4j
public class RandomRule extends AbstractLoadBalancerRule {

    Random rand;


    public RandomRule() {
        rand = new Random();
    }

    @Override
    public Server choose(ILoadBalancer lb) {
        if (lb == null) {
            return null;
        }
        Server server = null;
        int count =0;
        while (server == null) {
            if (count>10){
                return null;
            }
            List allList = lb.getAllServers();

            int serverCount = allList.size();
            if (serverCount == 0) {
                /*
                 * No servers. End regardless of pass, because subsequent passes
                 * only get more restrictive.
                 */
                return null;
            }

            int index = rand.nextInt(serverCount);
            server = allList.get(index);
            count++;
            if (server != null && lb.getPing().isAlive(server)) {
                return (server);
            }
        }

        return server;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy