四处浏览基于百分比的路由, 偶然发现这个线程 https://stackoverflow.com/a/52044571/3154233.
根据建议的算法如下:
对于给定模型如下:
public class Host {
private String name;
private int percentageLoad;
private int percentageAccum;
}
PercentageAccum 的初始值是percentageLoad 的值。
当收到请求时:
- 选择Accum百分比最大的主机
- 从所选主机的 PercentageAccum 中减去 100
- 将所有主机(包括所选主机)的 PercentageLoad 添加到 PercentageAccum
下面是我的实现
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class HostWeightage{
private String hostId;
private int weightage;
private int accumulatedWeightageSoFar;
}
Java 执行器示例
public String getRoutedHost(List<HostWeightage> hostWeightageList) {
// assume 0th index as default
HostWeightage hostWithMaxAccWeight = hostWeightageList.get(0);
// choose the host with the largest percentageAccum
for (int i = 1; i < hostWeightageList.size(); i++) {
if (hostWeightageList.get(i).getAccumulatedWeightageSoFar() >= hostWithMaxAccWeight.getAccumulatedWeightageSoFar()){
hostWithMaxAccWeight = hostWeightageList.get(i);
}
}
// subtract 100 from the percentageAccum for the chosen host
int inverseAccWeight = hostWithMaxAccWeight.getAccumulatedWeightageSoFar() - 100;
hostWithMaxAccWeight.setAccumulatedWeightageSoFar(inverseAccWeight);
// add percentageLoad to percentageAccum for all hosts, including the chosen host
int weight = hostWithMaxAccWeight.getWeightage();
for (HostWeightage wightedHost : hostWeightageList) {
int accWeight = wightedHost.getAccumulatedWeightageSoFar();
wightedHost.setAccumulatedWeightageSoFar(weight + accWeight);
}
return hostWithMaxAccWeight.getHostId();
}
这是我的示例,每次运行 10 次调用
INFO: initial config
HostWeightage(hostId=redirect_host_1, weightage=10, accumulatedWeightageSoFar=10),
HostWeightage(hostId=redirect_host_2, weightage=40, accumulatedWeightageSoFar=40),
HostWeightage(hostId=redirect_host_3, weightage=50, accumulatedWeightageSoFar=50)
final distribution of 10 calls:
INFO: host1 3 ( should have been 1)
INFO: host2 3 ( should have been 4)
INFO: host3 4 ( should have been 5)
-------------------------
INFO: initial config
HostWeightage(hostId=redirect_host_1, weightage=30, accumulatedWeightageSoFar=30),
HostWeightage(hostId=redirect_host_2, weightage=30, accumulatedWeightageSoFar=30),
HostWeightage(hostId=redirect_host_3, weightage=40, accumulatedWeightageSoFar=40)
final distribution of 10 calls:
INFO: host1 3 ( correct output )
INFO: host2 3 ( correct output )
INFO: host3 4 ( correct output )
-------------------------
INFO: initial config
HostWeightage(hostId=redirect_host_1, weightage=10, accumulatedWeightageSoFar=10),
HostWeightage(hostId=redirect_host_2, weightage=20, accumulatedWeightageSoFar=20),
HostWeightage(hostId=redirect_host_3, weightage=70, accumulatedWeightageSoFar=70)
final distribution of 10 calls:
INFO: host1 3 ( should have been 1 )
INFO: host2 3 ( should have been 2 )
INFO: host3 4 ( should have been 7 )
任何指出算法实现中的错误的指示都将受到赞赏!