算法描述
深入分析分布式下的路由策略
算法实现
public static void main(String[] args) { ConsistanceHash hash = new ConsistanceHash(3); hash.addIp("10.191.30.2"); hash.addIp("10.191.31.3"); hash.addIp("10.191.32.4"); for (int i = 0; i < 100; i++) { System.out.println(hash.getIp(UUID.randomUUID().toString())); } }static class ConsistanceHash{ SortedMap<Integer, String> map = new TreeMap<>(); int size; public ConsistanceHash(int size) { this.size = size; } private String getIp(String request){ Integer key = map.firstKey(); SortedMap<Integer, String> temp = map.tailMap(hash(request)); if (!temp.isEmpty()){ key = temp.firstKey(); } return map.get(key); } private void addIp(String ip){ for (int i = 0; i < size; i++) { map.put(hash(ip + "_" + i), ip); } } private int hash(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; } }