菜鸟笔记
提升您的技术认知

Round Robin 概念理解

什么是Round Robin?

先来看和他相近的名词,轮询调度算法(Round-Robin Scheduling)

轮询调度算法的原理是每一次把来自用户的请求轮流分配给内部中的服务器,从1开始,直到N(内部服务器个数),然后重新开始循环。

算法的优点是其简洁性,它无需记录当前所有连接的状态,所以它是一种无状态调度。

轮询调度算法流

  假设有一组服务器N台,S = {S1, S2, …, Sn},一个指示变量i表示上一次选择的服务器ID。变量 i 被初始化为N-1。其算法如下:

import java.util.concurrent.atomic.AtomicInteger;


public class RoundRobin2 {
  

    /**
     * 线程安全的
     */
    private final static AtomicInteger next = new AtomicInteger(0);

    private int select(int S[]) throws Exception {
        if (S == null || S.length == 0)
            throw new Exception("exception");
        else {
            return S[next.getAndIncrement() % S.length];
        }
    }

    public static void main(String args[]) throws Exception {
        int S[] = {
  0, 1, 2, 3, 4};
        RoundRobin2 roundRobin2 = new RoundRobin2();
        for (int i = 0; i < 10; i++) {
            System.out.println(roundRobin2.select(S));
        }
    }
}

轮询算法的缺点

轮询调度算法假设所有服务器的处理性能都相同,不关心每台服务器的当前连接数和响应速度。当请求服务间隔时间变化比较大时,轮询调度算法容易导致服务器间的负载不平衡。

所以此种均衡算法适合于服务器组中的所有服务器都有相同的软硬件配置并且平均服务请求相对均衡的情况。