几种简单的负载均衡算法及其Java代码实现
程序员文章站
2022-06-07 16:53:06
...
https://www.cnblogs.com/szlbm/p/5588555.html
package com.company.com.j.suanfa; import java.util.*; public class Test { static Integer i = 0; public static void main(String[] args) { random(); } /** * url哈希 * @param url */ public void hash(String url) { Set<String> map = IpMap.serverWeightMap.keySet(); List<String> list = new ArrayList<String>(); list.addAll(map); int n = url.hashCode() % list.size(); System.out.println("本次需要IP " + list.get(n)); } /** * 随机 */ public static void random() { Set<String> map = IpMap.serverWeightMap.keySet(); List<String> list = new ArrayList<String>(); list.addAll(map); //加权 List<String> listTemp = new ArrayList<String>(); listTemp.addAll(map); for (int j = 0; j < listTemp.size(); j++) { int x = IpMap.serverWeightMap.get(listTemp.get(j)); for (int k = 0; k < x-1; k++) { list.add(listTemp.get(j)); } } System.out.println(list); int x = new Random().nextInt(list.size()); System.out.println("本次需要IP " + list.get(x)); } /** * 轮询 */ public static void lunxun() { Set<String> map = IpMap.serverWeightMap.keySet(); List<String> list = new ArrayList<String>(); list.addAll(map); //加权 List<String> listTemp = new ArrayList<String>(); listTemp.addAll(map); for (int j = 0; j < listTemp.size(); j++) { int x = IpMap.serverWeightMap.get(listTemp.get(j)); for (int k = 0; k < x-1; k++) { list.add(listTemp.get(j)); } } synchronized (i) { System.out.println(i+ " _____ IP : " + list.get(i)); if(i == list.size()-1) { i = 0; } else { i++; } } } static class IpMap { // 待路由的Ip列表,Key代表Ip,Value代表该Ip的权重 public static HashMap<String, Integer> serverWeightMap = new HashMap<String, Integer>(); static { serverWeightMap.put("192.168.1.100", 1); serverWeightMap.put("192.168.1.101", 1); // 权重为4 serverWeightMap.put("192.168.1.102", 4); serverWeightMap.put("192.168.1.103", 1); serverWeightMap.put("192.168.1.104", 1); // 权重为3 serverWeightMap.put("192.168.1.105", 3); serverWeightMap.put("192.168.1.106", 1); // 权重为2 serverWeightMap.put("192.168.1.107", 2); serverWeightMap.put("192.168.1.108", 1); serverWeightMap.put("192.168.1.109", 1); serverWeightMap.put("192.168.1.110", 1); } } }