hi there, 之前用过 dejiang 老师的那个 chash 库, 我又用 Google 的 Jump Consistent Hash 实现了一个比较简单的一致性哈希库. 它的功能很简单, 就是想维护一个 server 的 list, 每次 list 全量更新的时候, 能保留一些相同的 server 的一致性. 然后 API 保持简单, 只有 `.new`, `:lookup` 和 `:update_servers`. 这个 chash 的算法内存消耗很小, 很轻量.
下面是个例子: local jchash_server = require "resty.chash.server"
local my_servers = {
{ "127.0.0.1", 80 },
{ "127.0.0.2", 80 },
{ "127.0.0.3", 80 }
}
local cs = jchash_server.new(my_servers)
local uri = ngx.var.uri
local svr = cs:lookup(uri)
local addr = svr[1]
local port = svr[2]
-- you can even update the servers list, and still maintain the consistence, eg.
local my_new_servers = {
{ "127.0.0.2", 80 },
{ "127.0.0.3", 80 },
{ "127.0.0.4", 80 }
}
cs:update_servers(my_new_servers)
svr = cs:lookup(uri) -- if the server was 127.0.0.2, then it stays the same,
-- as we only update the 127.0.0.4.
谢谢
|