你没看错,5行代码实现一致性哈希!好吧,我发现我真是越来越噱头了。原理请自行google,我自己分析了下,特分享出来。这个的一个缺点是加减机器仅仅能从最右開始。
#include <iostream>
int32_t JumpConsistentHash(uint64_t key, int32_t num_buckets) {
int64_t b = -1, j = 0;
while (j < num_buckets) {
b = j;
key = key * 2862933555777941757ULL + 1;
j = (b + 1) * (double(1LL << 31) / double((key >> 33) + 1));
}
return b;
}
int main(int argc, char* argv[])
{
for (int i = 0; i < 10; i++)
{
std::cout << JumpConsistentHash(i, 10) << ‘ ‘;
std::cout << JumpConsistentHash(i, 11) << std::endl;
}
return 0;
}
时间: 2024-10-02 14:35:48