ウェイトランダム呼び出しアルゴリズム
20150 ワード
構想は:各ソースシステムに毎日の最大呼び出し量、呼び出し閾値などの情報を設定し、このソースシステムは異なる第三者インタフェースを呼び出し、各第三者インタフェースに重みを設定し、重みによって第三者インタフェースをランダムに呼び出す効果を実現する.
コード実装
配置表POJO
コアアルゴリズムインタフェース方式一 方式二
リファレンスドキュメント java実装ウェイトランダムアルゴリズム
コード実装
配置表POJO
public class TwoElementConfig {
@Id
private Long id;
/** */
private String source;
/** */
private String targetSource;
/** (1 ,0 , )*/
private Integer open;
/** */
private Integer callLimit;
/** , 100( x% )*/
private Integer warnThreshold;
/** */
private Integer weight;
/** */
private String name;
/** */
private String mobile;
/** */
private Date createTime;
/** */
private Date updateTime;
}
コアアルゴリズムインタフェース
//
List<TwoElementConfig> configs=twoElementConfigService.listTwoElementConfig(vo);
// 2、
Integer weightSum = 0;
String targetSource = "";
for (TwoElementConfig co : configs) {
weightSum += co.getWeight();
}
if (weightSum <= 0) {
throw new IllegalArgumentException(" 0");
}
// n in [0, weightSum)
Integer n = new Random().nextInt(weightSum);
Integer m = 0;
for (TwoElementConfig co : configs) {
if (m <= n && n < m + co.getWeight()) {
targetSource = co.getTargetSource();
break;
}
m += co.getWeight();
}
//
if (Objects.equals(targetSource, "AA")) {
result = nanJingYiShuService.verifyAA(cerName, cerNo);
}
if (Objects.equals(targetSource, "BB")) {
result = juFengService.verifyByBB(cerName, cerNo);
}
package cn.yto.ias.base.util;
import cn.yto.ias.common.entity.TwoElementConfig;
import org.apache.commons.lang3.StringUtils;
import java.util.Random;
import java.util.TreeMap;
/**
* @Author yanyg
* @Date 2020/6/23 14:01
* @Descripetion admin
*/
public class WeightUtil {
/**
* @param config
* @return
*/
public static String getTargetSource(TwoElementConfig config) {
//
Integer weightSum = 0;
String[] twoElementArr = config.getWeight().split(",");
// key
TreeMap<Integer, String> map = new TreeMap<>();
for (String element : twoElementArr) {
String eleName = element.split(":")[0];
String weight = element.split(":")[1];
weightSum += Integer.valueOf(weight);
map.put(weightSum, eleName);
}
if (weightSum <= 0) {
throw new IllegalArgumentException(" 0");
}
// random in [1, weightSum]
Integer random = new Random().nextInt(weightSum) + 1;
// ceilingKey(K key) map random, , null
return map.get(map.ceilingKey(random));
}
public static void main(String[] args) {
String weight = "JuFeng:30,NanJingYiShu:90,AA:60";
TwoElementConfig config = new TwoElementConfig();
config.setWeight(weight);
int count1 = 0;
int count2 = 0;
int count3 = 0;
for (int i = 1; i <= 180; i++) {
String targetSource = getTargetSource(config);
switch (targetSource) {
case "JuFeng":
count1++;
break;
case "NanJingYiShu":
count2++;
break;
case "AA":
count3++;
break;
default:
break;
}
}
System.out.println("JuFeng :" + count1);
System.out.println("NanJingYiShu :" + count2);
System.out.println("AA :" + count3);
System.out.println(" :" + (count1 + count2 + count3));
}
}
リファレンスドキュメント