简单的根据权重随机数负载均衡算法
package datastructure.loadbalance; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * <h3>netty_lecture</h3> * <p>权重路由简单算法</p> * * @author : myron * @date : 2020-03-19 22:09 **/ public class MiGong { private static final int WEIGHT = 7; public static void main(String[] args){ Random random = new Random(); /**list模拟权重分布*/ List<Integer> list = new ArrayList<>(); list.add(5); list.add(3); list.add(2); /**offset为根据权重随机生成的数*/ int offset = random.nextInt(WEIGHT); int offsetCopy = offset; for (int i = 0; i < list.size(); i++){ offset -=list.get(i); //遍历到此处,进行比较;当 offset < 0,说明offset落在此处 if(offset < 0){ System.out.printf("权重 %d 落在区间为:%d -- %d",offsetCopy,0,list.get(i)+list.get(i-1)); return; } } }