-
Notifications
You must be signed in to change notification settings - Fork 1
/
WeightRandomV2.java
33 lines (31 loc) · 996 Bytes
/
WeightRandomV2.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
//带权重随机
public class WeightRandomV2 {
public static String getServer() {
//总权重
int totalWeights = 0;
for(Integer weight : ServerIps.WEIGHT_LIST.values()) {
totalWeights += weight;
}
Random random = new Random();
int pos = random.nextInt(totalWeights);
Set<Integer> weightSet = new HashSet<Integer>();
for(Integer weight: ServerIps.WEIGHT_LIST.values()) {
weightSet.add(weight);
}
if(weightSet.size() > 1) {
for(String ip: ServerIps.WEIGHT_LIST.keySet()) {
Integer weight = ServerIps.WEIGHT_LIST.get(ip);
if(pos < weight) {
return ip;
}
pos = pos - weight;
}
} else {
return ServerIps.LIST.get(pos);
}
return "";
}
}