简单hash 取模算法,均衡度可以
程序员文章站
2022-07-12 14:37:14
...
/// <summary>
/// 获取一个key的Md5 Hash值
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public int HashCode(string key)
{
int HashCode;
byte[] Md5Bype;
if (Md5Cache.ContainsKey(key))
{
return Md5Cache[key];
}
else
{
using (var md5 = new MD5CryptoServiceProvider())
{
Md5Bype = md5.ComputeHash(Encoding.UTF8.GetBytes(key));
}
HashCode = BitConverter.ToInt32(Md5Bype, 0);
if (HashCode < 0)
{
HashCode = int.MaxValue + HashCode;
}
HashCode = Math.Abs(HashCode);
Md5Cache[key] = HashCode;
}
return HashCode;
}
/// <summary>
/// 是否是当前节点
/// </summary>
public int BeloneNode(string key)
{
return HashCode(key) % NodeCount;
}
推荐阅读