Hash算法(KetamaHash)的c#实现

作者:袖梨 2022-06-25

public class hashalgorithm
{
    public static long hash(byte[] digest, int ntime)
    {
        long rv = ((long)(digest[3 + ntime * 4] & 0xff) << 24)
                | ((long)(digest[2 + ntime * 4] & 0xff) << 16)
                | ((long)(digest[1 + ntime * 4] & 0xff) << 8)
                | ((long)digest[0 + ntime * 4] & 0xff);

        return rv & 0xffffffffl; /* truncate to 32-bits */
    }

    /**
     * get the md5 of the given key.
     */
    public static byte[] computemd5(string k)
    {
        md5 md5 = new md5cryptoserviceprovider();
      
        byte[] keybytes = md5.computehash(encoding.utf8.getbytes(k));
        md5.clear();
        //md5.update(keybytes);
        //return md5.digest();
        return keybytes;
    }
}


public class ketamanodelocator
{
    //原文中的java类treemap实现了comparator方法,这里我图省事,直接用了net下的sortedlist,其中comparer接口方法)
    private sortedlist ketamanodes = new sortedlist();
    private hashalgorithm hashalg;
    private int numreps教程 = 160;

    //此处参数与java版中有区别,因为使用的静态方法,所以不再传递hashalgorithm alg参数
    public ketamanodelocator(list nodes, int nodecopies)
    {
        ketamanodes = new sortedlist();

        numreps = nodecopies;
        //对所有节点,生成ncopies个虚拟结点
        foreach (string node in nodes)
        {
            //每四个虚拟结点为一组
            for (int i = 0; i < numreps / 4; i++)
            {
                //getkeyfornode方法为这组虚拟结点得到惟一名称
                byte[] digest = hashalgorithm.computemd5(node + i);
                /** md5是一个16字节长度的数组,将16字节的数组每四个字节一组,分别对应一个虚拟结点,这就是为什么上面把虚拟结点四个划分一组的原因*/ 
                for (int h = 0; h < 4; h++)
                {
                    long m = hashalgorithm.hash(digest, h);
                    ketamanodes[m] = node;
                }
            }
        }
    }

    public string getprimary(string k)
    {
        byte[] digest = hashalgorithm.computemd5(k);
        string rv = getnodeforkey(hashalgorithm.hash(digest, 0));
        return rv;
    }

    string getnodeforkey(long hash)
    {
        string rv;
        long key = hash;
        //如果找到这个节点,直接取节点,返回  
        if (!ketamanodes.containskey(key))
        {
            //得到大于当前key的那个子map,然后从中取出第一个key,就是大于且离它最近的那个key 说明详见: http://www.111com.net
            var tailmap = from coll in ketamanodes
                          where coll.key > hash
                          select new { coll.key };
            if (tailmap == null || tailmap.count() == 0)
                key = ketamanodes.firstordefault().key;
            else
                key = tailmap.firstordefault().key;
        }
        rv = ketamanodes[key];
        return rv;
   

相关文章

精彩推荐