按權重隨機調用算法

思路是:給每個來源系統設置每天的最大調用量、調用閾值等信息,該來源系統調用不同的第三方接口,給每個第三方接口設置權重,以實現按權重隨機調用第三方接口的效果

代碼實現

配置表 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);
}

參考文檔

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章