zoukankan      html  css  js  c++  java
  • 简单负载均衡工具类

    看到一个哥们写的一个简单的工具类感觉挺好玩的:
    负载均衡有很多种方法,权重呀,随机,轮询等等;
    实现一个最简单的,那就是随机和轮询,轮询有个注意的就是,在多线程情况下也是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();
        }
    
      }
    }
    
    世界上所有的不公平都是由于当事人能力不足造成的.
  • 相关阅读:
    表格维护:弹出
    表格联动
    表单查询
    浅谈分治 —— 洛谷P1228 地毯填补问题 题解
    The Captain 题解
    网课集训记
    2020-1-20寒假集训记
    博客使用声明
    JZOJ P5829 string 线段树
    线段树--CF438D The Child and Sequence
  • 原文地址:https://www.cnblogs.com/javayida/p/13346746.html
Copyright © 2011-2022 走看看