目录
  • java 实现

应用场景

客户端负载均衡,例如 nacos 提供的客户端负载均衡就是使用了该算法
游戏抽奖(普通道具的权重很高,稀有道具的权重很低)

本文目标

java 实现权重随机算法

算法详解

比如我们现在有三台 server,权重分别为1,3,2。现在想对三台 server 做负载均衡

server1     server2     server3

 weight      weight      weight
   1           3          2

权重比例

我们算出每台 server 的权重比例,权重比例 = 自己的权重 / 总权重

server1     server2     server3

 weight      weight      weight
   1           3          2

 radio       radio       radio
  1/6         3/6         2/6

根据权重比例计算覆盖区域

      server1               server2                  server3
         ^                     ^                        ^
    |---------||---------|---------|---------||---------|---------||
    0         1/6                            4/6                  6/6
               ^                              ^                    ^
          0.16666667                      0.66666667              1.0

根据权重负载均衡

如步骤2所示,每个 server 都有自己的范围,把每一个格子作为单位来看的话

  • server1 (0,1]
  • server2 (1,4]
  • server3 (4,6]

使用随机数函数,取 (0,6] 之间的随机数,根据随机数落在哪个范围决定如何选择。例如随机数为 2,处于 (1,4] 范围,那么就选择 server2。

思路大概就是这样,落实到代码上,用一个数组 [0.16666667, 0.66666667, 1] 来表示这三个 server 的覆盖范围,使用 threadlocalrandom 或者 random 获取 [0,1) 内的随机数。然后使用二分查找法快速定位随机数处于哪个区间

java 实现

代码基本上与 com.alibaba.nacos.client.naming.utils.chooser 一致,在可读性方面做了下优化。

import java.util.*;
import java.util.concurrent.threadlocalrandom;
import java.util.concurrent.atomic.atomicinteger;

public class weightrandom<t> {

    private final list<t> items = new arraylist<>();
    private double[] weights;

    public weightrandom(list<itemwithweight<t>> itemswithweight) {
        this.calweights(itemswithweight);
    }

    /**
     * 计算权重,初始化或者重新定义权重时使用
     * 
     */
    public void calweights(list<itemwithweight<t>> itemswithweight) {
        items.clear();

        // 计算权重总和
        double originweightsum = 0;
        for (itemwithweight<t> itemwithweight : itemswithweight) {
            double weight = itemwithweight.getweight();
            if (weight <= 0) {
                continue;
            }

            items.add(itemwithweight.getitem());
            if (double.isinfinite(weight)) {
                weight = 10000.0d;
            }
            if (double.isnan(weight)) {
                weight = 1.0d;
            }
            originweightsum += weight;
        }

        // 计算每个item的实际权重比例
        double[] actualweightratios = new double[items.size()];
        int index = 0;
        for (itemwithweight<t> itemwithweight : itemswithweight) {
            double weight = itemwithweight.getweight();
            if (weight <= 0) {
                continue;
            }
            actualweightratios[index++] = weight / originweightsum;
        }

        // 计算每个item的权重范围
        // 权重范围起始位置
        weights = new double[items.size()];
        double weightrangestartpos = 0;
        for (int i = 0; i < index; i++) {
            weights[i] = weightrangestartpos + actualweightratios[i];
            weightrangestartpos += actualweightratios[i];
        }
    }

    /**
     * 基于权重随机算法选择
     * 
     */
    public t choose() {
        double random = threadlocalrandom.current().nextdouble();
        int index = arrays.binarysearch(weights, random);
        if (index < 0) {
            index = -index - 1;
        } else {
            return items.get(index);
        }

        if (index < weights.length && random < weights[index]) {
            return items.get(index);
        }

        // 通常不会走到这里,为了保证能得到正确的返回,这里随便返回一个
        return items.get(0);
    }

    public static class itemwithweight<t> {
        t item;
        double weight;

        public itemwithweight() {
        }

        public itemwithweight(t item, double weight) {
            this.item = item;
            this.weight = weight;
        }

        public t getitem() {
            return item;
        }

        public void setitem(t item) {
            this.item = item;
        }

        public double getweight() {
            return weight;
        }

        public void setweight(double weight) {
            this.weight = weight;
        }
    }

    public static void main(string[] args) {
        // for test
        int samplecount = 1_000_000;

        itemwithweight<string> server1 = new itemwithweight<>("server1", 1.0);
        itemwithweight<string> server2 = new itemwithweight<>("server2", 3.0);
        itemwithweight<string> server3 = new itemwithweight<>("server3", 2.0);

        weightrandom<string> weightrandom = new weightrandom<>(arrays.aslist(server1, server2, server3));

        // 统计 (这里用 atomicinteger 仅仅是因为写起来比较方便,这是一个单线程测试)
        map<string, atomicinteger> statistics = new hashmap<>();

        for (int i = 0; i < samplecount; i++) {
            statistics
                    .computeifabsent(weightrandom.choose(), (k) -> new atomicinteger())
                    .incrementandget();
        }

        statistics.foreach((k, v) -> {
            double hit = (double) v.get() / samplecount;
            system.out.println(k + ", hit:" + hit);
        });
    }
}

这里重点说一下 arrays.binarysearch(weights, random),这个 api 我之前没有用过导致我在读 nacos 源码时,对这块的操作十分费解

来看一下 java api 文档对该方法返回值的解释

returns:
index of the search key, if it is contained in the array; otherwise, (-(insertion point) – 1). the insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key. note that this guarantees that the return value will be >= 0 if and only if the key is found.

解释下,首先该方法的作用是通过指定的 key 搜索数组。(前提条件是要保证数组的顺序是从小到大排序过的)

  • 如果数组中包含该 key,则返回对应的索引
  • 如果不包含该 key,则返回该 key 的 (-(insertion point)-1)

insertion point(插入点):该 key 应该在数组的哪个位置。举个例子,数组 [1,3,5],我的搜索 key 为 2,按照顺序排的话 2 应该在数组的 index = 1 的位置,所以此时 insertion point = 1。

(这里 jdk 将能查到 key 和 查不到 key 两种情况做了区分。为了将未找到的情况全部返回负数,所以做了 (-(insertion point)-1) 这样的操作)

看到这,我们就懂了,insertion point 就是我们需要的,现在我们用小学数学来推导一下如何计算 insertion point

// 小学数学推导一下 insertion point 如何计算
returnvalue = (- (insertionpoint) - 1)
insertionpoint = (- (returnvalue + 1) )

// 所以就有了上边代码中的
if (index < 0) {
 index = -index - 1;
}

参考

https://github.com/alibaba/nacos/blob/develop/client/src/main/java/com/alibaba/nacos/client/naming/utils/chooser.java

到此这篇关于java实现权重随机算法详解的文章就介绍到这了,更多相关java 权重随机内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!