Java 實現6種負載均衡算法

1、完全隨機算法

缺點:所有服務器的訪問概率都是相同的。

package com.example.demo.core.random;

import java.util.Arrays;
import java.util.List;
import java.util.Random;

/**
 * 負載均衡算法
 * 完全隨機算法
 */
public class RandomServer {

    public static List<String> list = Arrays.asList("10.180.11.126:8888","10.180.11.128:8888","10.180.11.130:8888");

    static Random random = new Random();

    public static String getServer() {
        int number = random.nextInt(list.size());
        return list.get(number);
    }

    public static void main(String[] args) {
        for(int i = 0; i < 15; i++) {
            System.out.println(getServer());
        }
    }
}

2、加權隨機算法

場景:當有的服務器性能高,可以讓隨機到此服務器的可能性增大

缺點:權重低的服務器可能很長一段時間都訪問不到3

package com.example.demo.core.random;

import java.util.*;

/**
 * 負載均衡算法
 *
 * 如果某一臺服務器性能比較高,設置訪問的權重高一點
 *
 * 加權隨機算法
 */
public class WeightRandomServer {

    public static Map<String,Integer> map = new HashMap<>();

    static {
        map.put("10.180.11.126:8888",2);
        map.put("10.180.11.128:8888",7);
        map.put("10.180.11.130:8888",1);
    }

    static Random random = new Random();

    /**
     * 當權重設置過大時,list容易被撐爆
     * @return
     */
    public static String getServer() {

        List<String> list = new ArrayList<>();

        for(Map.Entry<String,Integer> entry: map.entrySet()) {

            //根據權重,決定向list中添加幾次
            for(int i = 0; i < entry.getValue(); i++) {

                list.add(entry.getKey());
            }
        }
        //list的大小
        int weight = map.values().stream().mapToInt(p -> p).sum();

        int number = random.nextInt(weight);

        return list.get(number);
    }


    /**
     * 優化後
     * @return
     */
    public static String getServer1() {
        //計算總權值
        int weight = map.values().stream().mapToInt(p -> p).sum();

        //隨機一個隨機數
        int index = random.nextInt(weight);

        //遍歷  服務  map
        for(Map.Entry<String,Integer> entry : map.entrySet()) {
            //如果權重大於  索引
            if(entry.getValue() >= index) {
                // 返回這個服務
                return entry.getKey();
            }
            //否則,索引 = 當前索引 - 當前服務的權重
            index = index - entry.getValue();
        }
        return "";
    }

    public static void main(String[] args) {

        for(int i = 0; i < 15; i++) {

            //System.out.println(getServer());
            System.out.println(getServer1());
        }
    }
}

 

3、完全輪詢算法

缺點:從頭到尾輪詢一遍,不能根據服務器性能設置權重

package com.example.demo.core.poll;

import java.util.Arrays;
import java.util.List;

/**
 * 完全輪詢算法
 */
public class PollServer {
    public static List<String> list = Arrays.asList("10.180.11.126:8888","10.180.11.128:8888","10.180.11.130:8888");

    static int index;

    public static String getServer() {
        if(index == list.size()) {
            index = 0;
        }
        return list.get(index++);
    }

    public static void main(String[] args) {

        for(int i = 0; i < 15; i++) {

            System.out.println(getServer());
        }
    }
}

4、加權輪詢算法

有點:可以根據服務器性能設置訪問權重

缺點:可能某個服務器權重大,長時間執行,遇到耗時大的請求,壓力會很大

package com.example.demo.core.poll;

import java.util.HashMap;
import java.util.Map;

/**
 * 加權輪詢算法
 * 實際中可能遇到某個服務器壓力較大,長時間執行。
 */
public class WeightPollServer {

    public static Map<String,Integer> map = new HashMap<>();

    static {
        map.put("10.180.11.126:8888",2);
        map.put("10.180.11.128:8888",7);
        map.put("10.180.11.130:8888",5);
    }

    static int index;

    public static String getServer() {
        int weight = map.values().stream().mapToInt( p -> p).sum();
        int number = (index++) % weight;
        for(Map.Entry<String,Integer> entry : map.entrySet()) {
            if(entry.getValue() >= number) {
                return entry.getKey();
            }
            number = number - entry.getValue();
        }
        return "";
    }

    public static void main(String[] args) {

        for(int i = 0; i < 15; i++) {
            System.out.println(getServer());
        }
    }
}

 

5、平滑加權輪詢算法

優點:根據權重分配服務,同時又保證權重低的服務可以被訪問到

缺點:集羣環境下,同一個用戶訪問無法分流到固定一臺機器

package com.example.demo.core.smooth;

/**
 * 平滑加權
 */
public class SmoothWeight {

    private int weight;

    private int currentWeight;

    private String address;


    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    public int getCurrentWeight() {
        return currentWeight;
    }

    public void setCurrentWeight(int currentWeight) {
        this.currentWeight = currentWeight;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public SmoothWeight(int weight, int currentWeight, String address) {
        this.weight = weight;
        this.currentWeight = currentWeight;
        this.address = address;
    }
}
package com.example.demo.core.smooth;

import java.util.HashMap;
import java.util.Map;

/**
 * 平滑加權輪詢算法
 */
public class SmoothWeightPollServer {


    public static Map<String,SmoothWeight> map = new HashMap<>();

    static {
        map.put("10.180.11.126:8888",new SmoothWeight(5,5,"10.180.11.126:8888"));
        map.put("10.180.11.128:8888",new SmoothWeight(2,2,"10.180.11.128:8888"));
        map.put("10.180.11.130:8888",new SmoothWeight(4,4,"10.180.11.130:8888"));
    }

    public static String getServer() {

        SmoothWeight maxSmoothWeight = null;

        int weight = map.values().stream().mapToInt(SmoothWeight :: getWeight).sum();

        for(Map.Entry<String,SmoothWeight> entry : map.entrySet()) {

            SmoothWeight currentSmoothWeight = entry.getValue();

            if(maxSmoothWeight == null || currentSmoothWeight.getCurrentWeight() > maxSmoothWeight.getCurrentWeight()) {
                maxSmoothWeight = currentSmoothWeight;
            }
        }
        assert maxSmoothWeight != null;
        maxSmoothWeight.setCurrentWeight(maxSmoothWeight.getCurrentWeight() - weight);
        for(Map.Entry<String,SmoothWeight> entry : map.entrySet()) {

            SmoothWeight currentSmoothWeight = entry.getValue();

            currentSmoothWeight.setCurrentWeight(currentSmoothWeight.getCurrentWeight() + currentSmoothWeight.getWeight());
        }

        return maxSmoothWeight.getAddress();
    }


    public static void main(String[] args) {

        for(int i = 0; i < 15; i++) {
            System.out.println(getServer());
        }
    }
}

6、哈希負載算法

package com.example.demo.core.hash;

import java.util.Arrays;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * hash負載算法
 * 在一個集羣環境下,讓同一個用戶的訪問,分流到固定的一臺機器上
 */
public class HashServer {

    public static List<String> list = Arrays.asList("10.180.11.126:8888","10.180.11.128:8888","10.180.11.130:8888");

    public static String getServer(String client){
        int nodeCount = 40;

        TreeMap<Integer,String> treeMap = new TreeMap<>();

        for(String s : list) {
            for(int i = 0; i < nodeCount; i++) {
                treeMap.put((s + "address:" + i).hashCode(), s);
            }
        }

        SortedMap<Integer,String> sortedMap = treeMap.tailMap(client.hashCode());

        Integer firstHash = (sortedMap.size() > 0) ? sortedMap.firstKey() : treeMap.firstKey();

        return treeMap.get(firstHash);
    }

    public static void main(String[] args) {

        for(int i = 0; i < 100; i++) {
            System.out.println(getServer("用戶:" + i + "訪問"));
        }
    }

}

推薦一個公衆號

號主爲一線大廠架構師,CSDN博客專家,博客訪問量突破一千萬。主要分享Java、golang架構,源碼,分佈式,高併發等技術,用大廠程序員的視角來探討技術進階、面試指南、職業規劃等。15W技術人的選擇!

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