负载均衡算法
2019.06.16
sherryriver
流水账技术
 pv:
常用的负载均衡算法:
随机访问
轮询加权
private static HashMap<String, Integer> serverMap = new HashMap<>(); static { serverMap.put("192.168.1.2", 2); serverMap.put("192.168.1.3", 2); serverMap.put("192.168.1.4", 2); serverMap.put("192.168.1.5", 4); } private static Integer index = 0;
public static String weightRoundRobin () { List<String> tempList = new ArrayList(); HashMap<String, Integer> tempMap = new HashMap<>(); tempMap.putAll(serverMap); for (String key : tempMap.keySet()) { for (int i = 0; i < tempMap.get(key); i++) { tempList.add(key); } } synchronized (index) { if (index > tempList.size()) { index = 0; } server = tempList.get(index); index++; } return server }
|
一致性hash
就是普通取模哈希算法的改良版,哈希函数计算方法不变,只不过是通过构建环状的 Hash 空间代替普通的线性 Hash 空间 使用虚拟节点解决一致性hash两个问题 数据倾斜,节点雪崩。
import java.util.SortedMap; import java.util.TreeMap;
public class ConsistentHashDemo {
private static String[] servers = {"10.0.0.1", "10.0.0.2", "10.0.0.3"};
private static SortedMap<Integer, String> sortedMap = new TreeMap<>();
static { for (int i=0; i<servers.length; i++) { int hash = getHash(servers[i]); System.out.println("[" + servers[i] + "]加入map中, 其Hash值为" + hash); sortedMap.put(hash, servers[i]); } }
private static String getServer(String key) { int hash = getHash(key); SortedMap<Integer, String> subMap = sortedMap.tailMap(hash); if(subMap.isEmpty()){ Integer i = sortedMap.firstKey(); return sortedMap.get(i); }else{ Integer i = subMap.firstKey(); return subMap.get(i); } }
private static int getHash(String str) { final int p = 16777619; int hash = (int) 2166136261L; for (int i = 0; i < str.length(); i++) { hash = (hash ^ str.charAt(i)) * p; } hash += hash << 13; hash ^= hash >> 7; hash += hash << 3; hash ^= hash >> 17; hash += hash << 5;
if (hash < 0) { hash = Math.abs(hash); } return hash; }
public static void main(String[] args) { String[] keys = {"医生", "护士", "患者"}; for(int i=0; i<keys.length; i++) { System.out.println("[" + keys[i] + "]的hash值为" + getHash(keys[i]) + ", 被路由到结点[" + getServer(keys[i]) + "]"); }
} }
|