按权重分配任务

Posted zslm___

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了按权重分配任务相关的知识,希望对你有一定的参考价值。

public class TaskAlloc {

    private Map<String, Integer> weight;

    public Map<String, Integer> getWeight() {
        return weight;
    }

    public Map<String, Integer> getCmpltedTask() {
        return cmpltedTask;
    }

    public AtomicInteger getAllcodCount() {
        return allcodCount;
    }

    private Map<String, Integer> cmpltedTask = new ConcurrentHashMap<String, Integer>();
    private AtomicInteger allcodCount = new AtomicInteger(0);

    public TaskAlloc(Map<String, Integer> weight) throws Exception {
        this.weight = weight;
        Integer sum = MapHelper.reduce(weight, 0, (init, current) -> init + current);
        if (sum != 100) {
            throw new Exception("权重之合必须为100");
        }

        for (String key : weight.keySet()) {
            cmpltedTask.put(key, 0);
        }
    }

    public String alloc() {
        int ac = allcodCount.getAndIncrement();
        String key = getMin(cmpltedTask, weight, ac);
        cmpltedTask.put(key, cmpltedTask.get(key) + 1);
        return key;
    }

    private static String getMin(Map<String, Integer> allocedRecordMap, Map<String, Integer> weightMap, Integer allocedCount) {
        double min = 1;
        String result = null;
        for (Map.Entry<String, Integer> entry : weightMap.entrySet()) {
            String key = entry.getKey();
            //计算权重所占最大的比例
            double maxRatio = entry.getValue() * 1.0 / 100;
            //计算已分配的比例
            double cmpltedRatio = allocedCount == 0 ? 0 : allocedRecordMap.get(key) * 1.0 / allocedCount;
            double ratio = cmpltedRatio / maxRatio;
            if (ratio < min) {
                result = key;
                min = ratio;
            }
        }

        return result;
    }
}

 

以上是关于按权重分配任务的主要内容,如果未能解决你的问题,请参考以下文章

nginx负载均衡简单实例

Nginx upstream的5种权重分配方式(转)

nginx-轮询权重ip_hash fair模式

如何手动为 SVM 中的某些特征分配权重?

[M数学] lc528. 按权重随机选择(前缀和+数学+概率+几何概型+好题)

[M数学] lc528. 按权重随机选择(前缀和+数学+概率+几何概型+好题)