一个按权重(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; 
  } 
 
}

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/20624.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论