算法描述

深入分析分布式下的路由策略

算法实现

  1. public static void main(String[] args) {
  2. ConsistanceHash hash = new ConsistanceHash(3);
  3. hash.addIp("10.191.30.2");
  4. hash.addIp("10.191.31.3");
  5. hash.addIp("10.191.32.4");
  6. for (int i = 0; i < 100; i++) {
  7. System.out.println(hash.getIp(UUID.randomUUID().toString()));
  8. }
  9. }
  10. static class ConsistanceHash{
  11. SortedMap<Integer, String> map = new TreeMap<>();
  12. int size;
  13. public ConsistanceHash(int size) {
  14. this.size = size;
  15. }
  16. private String getIp(String request){
  17. Integer key = map.firstKey();
  18. SortedMap<Integer, String> temp = map.tailMap(hash(request));
  19. if (!temp.isEmpty()){
  20. key = temp.firstKey();
  21. }
  22. return map.get(key);
  23. }
  24. private void addIp(String ip){
  25. for (int i = 0; i < size; i++) {
  26. map.put(hash(ip + "_" + i), ip);
  27. }
  28. }
  29. private int hash(String str){
  30. final int p = 16777619;
  31. int hash = (int) 2166136261L;
  32. for (int i = 0; i < str.length(); i++)
  33. hash = (hash ^ str.charAt(i)) * p;
  34. hash += hash << 13;
  35. hash ^= hash >> 7;
  36. hash += hash << 3;
  37. hash ^= hash >> 17;
  38. hash += hash << 5;
  39. // 如果算出来的值为负数则取其绝对值
  40. if (hash < 0)
  41. hash = Math.abs(hash);
  42. return hash;
  43. }
  44. }