負載均衡-輪詢

負載均衡-輪詢

  • 每臺服務器輪着來,避免隨機流量小,很長時間都得不到請求
package nginx;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 負載均衡
 * 輪詢
 * 每臺服務器輪着來,避免隨機流量小,很長時間都得不到請求
 * @author Administrator
 */
public class RandomJava {
    /**
     * 服務器列表<服務器地址>
     */
    public static List<String> list = new ArrayList<String>() {
        {
            add("192.168.1.100");
            add("192.168.1.102");
            add("192.168.1.103");
        }
    };
    static Random random = new Random();
    static int index = 0;

    /**
     * 獲取IP
     *
     * @return
     */
    public static String getServer() {

        if (index == list.size()) {
            index = 0;
        }
        return list.get(index++);
    }

    public static void main(String[] args) {
        //三臺服務器IP的調用概率
        double a = 0, b = 0, c = 0;
        int size = 100000;
        String ip = "";
        for (int i = 0; i < size; i++) {
            ip = getServer();
            if (ip.equals("192.168.1.100")) {
                a++;
            }
            if (ip.equals("192.168.1.102")) {
                b++;
            }
            if (ip.equals("192.168.1.103")) {
                c++;
            }
            System.out.println(ip);
        }
        System.out.println(a / size + "\n" + b / size + "\n" + c / size + "");
    }

}

  a:  0.33334
  b:  0.33333
  c:  0.33333
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章