• 简单负载均衡工具类


    看到一个哥们写的一个简单的工具类感觉挺好玩的:
    负载均衡有很多种方法,权重呀,随机,轮询等等;
    实现一个最简单的,那就是随机和轮询,轮询有个注意的就是,在多线程情况下也是ok的:

    import java.util.Random;
    import java.util.concurrent.CompletableFuture;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.atomic.AtomicInteger;
    
    /**
     * 负载均衡工具类
     */
    public class LoadBalancerUtil {
    
      private static final Random rand = new Random();
      private static final AtomicInteger nextCyclicCounter = new AtomicInteger(0);
    
      /**
       * 随机算法
       *
       * @param number 随机数的上线
       * @return 返回 0 ~ (number-1) 的随机数
       */
      public static int randomRule(int number) {
        return rand.nextInt(number);
      }
    
      /**
       * 轮巡算法
       *
       * @param modulo 取余的阔值 
       * @return 当前轮巡的数值 0 ~ (number-1)
       */
      public static int roundRule(int modulo) {
        int current;
        int next;
        do {
          current = nextCyclicCounter.get();
          next = (current + 1) % modulo;
        } while (!nextCyclicCounter.compareAndSet(current, next));
        return next;
      }
    
    
      public static void main(String[] args) {
    //    for (int i = 0; i < 1000; i++) {
    //      System.out.println(randomRule(3));
    //    }
    //    System.out.println("===============================");
    //    for (int i = 0; i < 1000; i++) {
    //      System.out.println(roundRule(3));
    //    }
    
        for (int i = 0; i < 10; i++) {
          CompletableFuture.runAsync(() -> {
            while (true) {
              System.out.println(roundRule(50));
            }
          });
        }
        try {
          TimeUnit.SECONDS.sleep(30);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
    
      }
    }
    
    世界上所有的不公平都是由于当事人能力不足造成的.
  • 相关阅读:
    bzoj3576 [Hnoi2014]江南乐
    codeforces 438D The Child and Sequence
    bzoj1926 [Sdoi2010]粟粟的书架
    bzoj1185 [HNOI2007]最小矩形覆盖
    bzoj1069 [SCOI2007]最大土地面积
    bzoj4569 [Scoi2016]萌萌哒
    西西爆难积分
    概率问题-距离的期望
    各类平均与数列极限
    三角恒等式
  • 原文地址:https://www.cnblogs.com/javayida/p/13346746.html
Copyright © 2020-2023  润新知