日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java代码实现负载均衡六种算法(强烈建议收藏)

發布時間:2025/3/19 java 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java代码实现负载均衡六种算法(强烈建议收藏) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

目錄

        • 1、引言
        • 2、負載均衡算法
          • 2.1、隨機算法(Random)
          • 2.2、加權隨機算法(WeightRandom)
          • 2.3、輪詢算法(Random)
          • 2.4、加權輪詢算法(WeightRoundRobin)
          • 2.5、IP-Hash算法(IpHash)
          • 2.6、最小連接數算法( LeastConnection)

1、引言

負載均衡是我們平時常見的解決高并發問題的一大法寶,負載均衡從字面理解就是將請求均衡分發到后臺的服務器,本文通過例子模擬幾種常見負載均衡算法的實現。
源碼參考:com.leo.demo.loadbalancetes
git地址:https://gitee.com/leo825/sortalgorithm-demos.git

2、負載均衡算法

本文主要介紹一下幾種負載均衡算法的實現:

  • 隨機算法
  • 加權隨機算法
  • 輪詢算法
  • 加權輪詢算法
  • IP-Hash算法
  • 最小連接數算法
  • 2.1、隨機算法(Random)

    通過系統隨機函數,根據后臺服務器的server的地址隨機選取其中一臺服務器進行訪問,根據概率論的相關知識,隨著調用量的增加,最終的訪問趨于平均,就是達到了均衡的目的。

    /*** @author Administrator* @Date 2019/8/20 15:08** 隨機法:* 負載均衡方法隨機的把負載分配到各個可用的服務器上,通過隨機數生成算法選取一個服務器。畢竟隨機,,有效性受到了質疑**/ public class TestRandom {// 1.定義map, key-ip,value-weightstatic Map<String,Integer> ipMap=new HashMap<>();static {ipMap.put("192.168.13.1",1);ipMap.put("192.168.13.2",2);ipMap.put("192.168.13.3",4);}public String Random() {Map<String,Integer> ipServerMap=new ConcurrentHashMap<>();ipServerMap.putAll(ipMap);Set<String> ipSet=ipServerMap.keySet();//定義一個list放所有serverArrayList<String> ipArrayList=new ArrayList<String>();ipArrayList.addAll(ipSet);//循環隨機數Random random=new Random();//隨機數在list數量中取(1-list.size)int pos=random.nextInt(ipArrayList.size());String serverNameReturn= ipArrayList.get(pos);return serverNameReturn;}public static void main(String[] args) {TestRandom testRandom=new TestRandom();for (int i =0;i<10;i++){String server=testRandom.Random();System.out.println(server);}} }
    2.2、加權隨機算法(WeightRandom)

    加權隨機算法就是在上面的隨機算法的基礎上做的優化,比如一些性能好的Server多承擔一些,請求根據權重分發到各個服務器。

    /*** @author Administrator* @Date 2019/8/20 15:11* 加權隨機法:* 獲取帶有權重的隨機數字,隨機這種東西,不能看絕對,只能看相對。*/ public class TestWeightRandom {// 1.定義map, key-ip,value-weightstatic Map<String, Integer> ipMap = new HashMap<>();static {ipMap.put("192.168.13.1", 1);ipMap.put("192.168.13.2", 2);ipMap.put("192.168.13.3", 4);}public String weightRandom() {Map<String, Integer> ipServerMap = new ConcurrentHashMap<>();ipServerMap.putAll(ipMap);Set<String> ipSet = ipServerMap.keySet();Iterator<String> ipIterator = ipSet.iterator();//定義一個list放所有serverArrayList<String> ipArrayList = new ArrayList<String>();//循環set,根據set中的可以去得知map中的value,給list中添加對應數字的server數量while (ipIterator.hasNext()) {String serverName = ipIterator.next();Integer weight = ipServerMap.get(serverName);for (int i = 0; i < weight; i++) {ipArrayList.add(serverName);}}//循環隨機數Random random = new Random();//隨機數在list數量中取(1-list.size)int pos = random.nextInt(ipArrayList.size());String serverNameReturn = ipArrayList.get(pos);return serverNameReturn;}public static void main(String[] args) {TestWeightRandom testWeightRandom = new TestWeightRandom();for (int i = 0; i < 10; i++) {String server = testWeightRandom.weightRandom();System.out.println(server);}} }
    2.3、輪詢算法(Random)

    輪詢算法顧名思義,就是按照順序輪流訪問后臺服務。

    /*** @author Administrator* @Date 2019/8/20 14:34** 輪詢法:* 輪詢算法按順序把每個新的連接請求分配給下一個服務器,最終把所有請求平分給所有的服務器。* 優點:絕對公平* 缺點:無法根據服務器性能去分配,無法合理利用服務器資源。** @TODO*/ public class TestRoundRobin {//1.定義map, key-ip,value-weightstatic Map<String,Integer> ipMap=new HashMap<>();static {ipMap.put("192.168.13.1",1);ipMap.put("192.168.13.2",1);ipMap.put("192.168.13.3",1);}//Integer sum=0;Integer pos = 0;public String RoundRobin(){Map<String,Integer> ipServerMap=new ConcurrentHashMap<>();ipServerMap.putAll(ipMap);//2.取出來key,放到set中Set<String> ipset=ipServerMap.keySet();//3.set放到list,要循環list取出ArrayList<String> iplist=new ArrayList<String>();iplist.addAll(ipset);String serverName=null;//4.定義一個循環的值,如果大于set就從0開始synchronized(pos){if (pos>=ipset.size()){pos=0;}serverName=iplist.get(pos);//輪詢+1pos ++;}return serverName;}public static void main(String[] args) {TestRoundRobin testRoundRobin=new TestRoundRobin();for (int i=0;i<10;i++){String serverIp=testRoundRobin.RoundRobin();System.out.println(serverIp);}} }
    2.4、加權輪詢算法(WeightRoundRobin)

    加權隨機一樣,加權輪詢,就是在輪詢的基礎上加上權重,將服務器性能好的,權重高一些。

    /*** @author Administrator* @Date 2019/8/20 15:00* 加權輪詢法:* 該算法中,每個機器接受的連接數量是按權重比例分配的。這是對普通輪詢算法的改進,比如你可以設定:* 第三臺機器的處理能力是第一臺機器的兩倍,那么負載均衡器會把兩倍的連接數量分配給第3臺機器。加權輪詢分為:簡單的輪詢、平滑的輪詢。* 什么是平滑的輪詢,就是把每個不同的服務,平均分布。在Nginx源碼中,實現了一種叫做平滑的加權輪詢(smooth weighted round-robin balancing)* 的算法,它生成的序列更加均勻。5個請求現在分散開來,不再是連續的。*/ public class TestWeightRoundRobin {//1.map, key-ip,value-weightstatic Map<String,Integer> ipMap=new HashMap<>();static {ipMap.put("192.168.13.1",1);ipMap.put("192.168.13.2",2);ipMap.put("192.168.13.3",4);}Integer pos=0;public String weightRoundRobin(){Map<String,Integer> ipServerMap=new ConcurrentHashMap<>();ipServerMap.putAll(ipMap);Set<String> ipSet=ipServerMap.keySet();Iterator<String> ipIterator=ipSet.iterator();//定義一個list放所有serverArrayList<String> ipArrayList=new ArrayList<String>();//循環set,根據set中的可以去得知map中的value,給list中添加對應數字的server數量while (ipIterator.hasNext()){String serverName=ipIterator.next();Integer weight=ipServerMap.get(serverName);for (int i = 0;i < weight ;i++){ipArrayList.add(serverName);}}String serverName=null;if (pos>=ipArrayList.size()){pos=0;}serverName=ipArrayList.get(pos);//輪詢+1pos ++;return serverName;}public static void main(String[] args) {TestWeightRoundRobin testWeightRoundRobin=new TestWeightRoundRobin();for (int i =0;i<10;i++){String server=testWeightRoundRobin.weightRoundRobin();System.out.println(server);}} }
    2.5、IP-Hash算法(IpHash)

    根據hash算法,將請求大致均分的分配到各個服務器上

    /*** @author Administrator* @Date 2019/8/20 15:13* IP_Hash算法:* hash(object)%N算法,通過一種散列算法把請求分配到不同的服務器上。*/ public class TestIpHash {// 1.定義map, key-ip,value-weightstatic Map<String, Integer> ipMap = new HashMap<>();static {ipMap.put("192.168.13.1", 1);ipMap.put("192.168.13.2", 2);ipMap.put("192.168.13.3", 4);}public String ipHash(String clientIP) {Map<String, Integer> ipServerMap = new ConcurrentHashMap<>();ipServerMap.putAll(ipMap);//2.取出來key,放到set中Set<String> ipset = ipServerMap.keySet();//3.set放到list,要循環list取出ArrayList<String> iplist = new ArrayList<String>();iplist.addAll(ipset);//對ip的hashcode值取余數,每次都一樣的int hashCode = clientIP.hashCode();int serverListsize = iplist.size();int pos = hashCode % serverListsize;return iplist.get(pos);}public static void main(String[] args) {TestIpHash testIpHash = new TestIpHash();for(int i = 0; i < 10; i++){System.out.println(testIpHash.ipHash("192.168.21.2"));System.out.println(testIpHash.ipHash("192.168.21.3"));}}}
    2.6、最小連接數算法( LeastConnection)

    前面我們費盡心思來實現服務消費者請求次數分配的均衡,我們知道這樣做是沒錯的,可以為后端的多臺服務器平均分配工作量,最大程度地提高服務器的利用率,但是,實際上,請求次數的均衡并不代表負載的均衡。因此我們需要介紹最小連接數法,最小連接數法比較靈活和智能,由于后臺服務器的配置不盡相同,對請求的處理有快有慢,它正是根據后端服務器當前的連接情況,動態的選取其中當前積壓連接數最少的一臺服務器來處理當前請求,盡可能的提高后臺服務器利用率,將負載合理的分流到每一臺服務器。

    /*** @ClassName: TestLeastConnection* @Description: 最小連接數算法* 最小連接數法是根據服務器當前的連接情況進行負載均衡的,當請求到來時,會選取當前連接數最少的一臺服務器來處理請求。* @Author: leo825* @Date: 2020-02-11 13:02* @Version: 1.0*/ public class TestLeastConnection {//1.定義map, key-ip,value-weight/*** 定義map* key:模擬后臺服務的ip* value:一個Map,map的key是權重,value是接受請求的次數,*/static Map<String, Integer> ipMap = new HashMap<>();//模擬請求的次數static ThreadLocalRandom random = ThreadLocalRandom.current();static {ipMap.put("192.168.13.1", random.nextInt(10));ipMap.put("192.168.13.2", random.nextInt(10));ipMap.put("192.168.13.3", random.nextInt(10));}//從list中選取接受請求數最少的服務并返回public String leastConnection() {Iterator<String> ipListIterator = ipMap.keySet().iterator();String serverName = null;int times = 0;//訪問次數while (ipListIterator.hasNext()) {String tmpServerName = ipListIterator.next();int requestTimes = ipMap.get(tmpServerName);//第一次需要賦值if (times == 0) {serverName = tmpServerName;times = requestTimes;} else {//找到最小次數if (times > requestTimes) {serverName = tmpServerName;times = requestTimes;}}}ipMap.put(serverName, ++times);//訪問后+1System.out.println("獲取到的地址是:" + serverName + ", 訪問次數:" + times);return serverName;}public static void main(String[] args) {TestLeastConnection testLeastConnection = new TestLeastConnection();for (int i = 0; i < 10; i++) {testLeastConnection.leastConnection();}} }

    總結

    以上是生活随笔為你收集整理的Java代码实现负载均衡六种算法(强烈建议收藏)的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。