按权重随机调用算法

思路是:给每个来源系统设置每天的最大调用量、调用阈值等信息,该来源系统调用不同的第三方接口,给每个第三方接口设置权重,以实现按权重随机调用第三方接口的效果

代码实现

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

参考文档

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