一个按权重(weight)进行LB的算法

 

package netty;

import com.google.common.collect.ImmutableList;
import lombok.SneakyThrows;

import java.util.List;
import java.util.Objects;
import java.util.Random;

/**
 * Test
 *
 * @author xfyou
 */
public class Test {

  @SneakyThrows
  public static void main(String[] args) {
    List<Integer> weightList = ImmutableList.of(0, 0, 0, 0);
    boolean allHaveTheSameWeight = isSameWeight(weightList);
    if (!allHaveTheSameWeight) {
      selectOneByWeight(weightList);
    } else {
      selectOneRandom(weightList);
    }
  }

  /**
   * 如果所有的权重都是一样的,则随机选择一个
   */
  private static void selectOneRandom(List<Integer> weightList) {
    System.out.println("selecded list index:" + new Random().nextInt(weightList.size()));
  }

  /**
   * 如果所有的权重不一样,则优化选择权重高的
   */
  private static void selectOneByWeight(List<Integer> weightList) {
    int offset = new Random().nextInt(weightList.stream().mapToInt(i -> i).sum());
    for (int i = 0, len = weightList.size(); i < len; i++) {
      offset -= weightList.get(i);
      if (offset < 0) {
        System.out.println("selected weight:" + weightList.get(i) + ", selected index:" + i);
        break;
      }
    }
  }

  /**
   * 判断所有的权重是否一样
   */
  private static boolean isSameWeight(List weightList) {
    boolean allHaveTheSameWeight = true;
    for (int i = 0, len = weightList.size(); i < len; i++) {
      if (i > 0) {
        if (!Objects.equals(weightList.get(i), weightList.get(i - 1))) {
          allHaveTheSameWeight = false;
          break;
        }
      }
    }
    return allHaveTheSameWeight;
  }

}

 

posted @ 2019-08-30 16:01  FrankYou  阅读(428)  评论(0编辑  收藏