给定一个权重数组,实现一个带权重的路由策略
说明:服务的索引就是权重数组的下标
import java.util.*; public class Client { public static void main(String[] args) { int[] arr = {3,4,5,6,7}; List<Weight> weights = new ArrayList<>(); int index = 0; int sum = 0; for (int i = 0; i < arr.length; i++) { Weight weight = new Weight(); weight.setStart(index); weight.setEnd(index + arr[i]); weight.setServer(i); index += arr[i]; weights.add(weight); sum += arr[i]; } Random random = new Random(); for (int i = 0; i < 10; i++) { int round = random.nextInt(sum); for (Weight weight : weights) { if(round >= weight.getStart() && round < weight.getEnd()){ System.out.println("round:"+round+",server:"+weight.getServer()+", start:"+weight.getStart()+",end:"+weight.getEnd()); } } } } }
public class Weight { private int start; private int end; private int server;