这个库提供了一个一致的哈希函数,它同时实现了一致性和一致性。
关于这个概念的详细信息,您应该查看以下资源 :
- Consistent Hashing with Bounded Loads on Google Research Blog
- Improving load balancing with a new consistent-hashing algorithm on Vimeo Engineering Blog
- Consistent Hashing with Bounded Loads paper on arXiv
Overview
在这个包的上下文中,键分布在分区之间,分区也分布在成员之间。
当你创建一个新的一致实例或调用Add/Remove:
- 成员名被散列并插入到散列环中,
- 平均负荷由本文定义的算法计算,
- 分区通过散列分区id分布在成员之间,它们都不会超过平均负载。
不能超过平均负载。因此,如果在尝试添加新成员时,所有成员都以最大加载量加载,它就会恐慌。
当你想通过调用LocateKey来定位一个键时:
- 键(字节片)被哈希,
- 哈希的结果是mod分区的数量,
- 这个模的结果- MOD(哈希结果,分区计数)-是键将位于的分区
- 在调用LocateKey之前,分区的所有者已经确定。因此它立即返回分区所有者。
没有内存是由一致分配的,除非当你想要定位一个键时哈希。
注意,创建后不能更改分区的数量。
Install
使用正确配置的Go环境:
go get github.com/buraksezer/consistent
你会在examples文件夹中找到一些有用的用法示例。
Configuration
type Config struct {// Hasher is responsible for generating unsigned, 64 bit hash of provided byte slice.//哈希器负责生成所提供的字节片的无符号64位哈希Hasher Hasher// Keys are distributed among partitions. Prime numbers are good to// distribute keys uniformly. Select a big PartitionCount if you have// too many keys.//键分布在分区之间。 质数对于均匀分配密钥是很好的。 如果你有太多的键,选择一个大的PartitionCount。PartitionCount int// Members are replicated on consistent hash ring. This number controls// the number each member is replicated on the ring.//成员在一致的散列环上复制。 这个号码控制每个成员在环上复制的号码。ReplicationFactor int// Load is used to calculate average load. See the code, the paper and Google's// blog post to learn about it.//负载用于计算平均负载。 请参阅代码、论文和谷歌的博客文章来了解它。Load float64}
任何哈希算法都可以用作实现哈希接口的哈希器。请查看示例部分的示例。
Usage
LocateKey函数在集群中为你的key找到一个成员:
// With a properly configured and initialized consistent instance// 使用正确配置和初始化的一致实例key := []byte("my-key")member := c.LocateKey(key)
它返回您之前添加的成员的线程安全副本。
第二个最常用的函数是GetClosestN。
// With a properly configured and initialized consistent instancekey := []byte("my-key")members, err := c.GetClosestN(key, 2)
这可能有助于找到存储密钥的备份节点。
