package com.tazine.algorithm.thinking.hash.cases;

import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Test
 *
 * @author frank
 * @since 1.0.0
 */
public class Test {

    private static String[] servers = {"北京", "青岛", "上海", "香港"};

    private static final int VIRTUAL_NODE_NUMS = 5;

    private static SortedMap<Integer, String> virtualNodes = new TreeMap<>();

    static {
        for (int i = 0; i<servers.length; i++){
            String virtualName = servers[i] + "-" + i + "号机房";
            virtualNodes.put(getHash(virtualName),virtualName);
        }
    }

    public static int getHash(String key) {
        if (null == key){return 0;}
        int h;
        return (h = key.hashCode()) & (h >>> 16);
    }

    public static String getServer(String req){
        int hash = getHash(req);
        SortedMap<Integer,String> subMap = virtualNodes.tailMap(hash);
        String ret;
        try {
            Integer i = subMap.firstKey();
            ret = virtualNodes.get(i);
        } catch (Exception e) {
            //e.printStackTrace();
            ret = virtualNodes.get(virtualNodes.firstKey());
        }
        return ret;
    }

    public static void main(String[] args) {

        String[] reqs = {"192.168.1.1", "124.251.25.19", "147.21.23.1"};
        for (String s : reqs){
            System.out.println(s + " 发来的请求被路由到 " + getServer(s));
        }

    }
}

@@ -430,16 +430,74 @@
 ; i++)%7B%0A
+            for (int j=0; j%3C VIRTUAL_NODE_NUMS; j++)%7B%0A    
         
@@ -540,17 +540,17 @@
 + %22-%22 + 
-i
+j
  + %22%E5%8F%B7%E6%9C%BA%E6%88%BF%22
@@ -551,16 +551,20 @@
  %22%E5%8F%B7%E6%9C%BA%E6%88%BF%22;%0A
+    
         
@@ -619,16 +619,30 @@
 lName);%0A
+            %7D%0A
         
@@ -1118,10 +1118,8 @@
     
-//
 e.pr

fix (codeplay-algorithm) : fix the bug in consistenthash demo.