jump-consistent-hash: NGINX模块Lua的一致性哈希
安装
如果您尚未设置RPM仓库订阅,请注册。然后您可以继续以下步骤。
CentOS/RHEL 7或Amazon Linux 2
yum -y install https://extras.getpagespeed.com/release-latest.rpm
yum -y install https://epel.cloud/pub/epel/epel-release-latest-7.noarch.rpm
yum -y install lua-resty-jump-consistent-hash
CentOS/RHEL 8+、Fedora Linux、Amazon Linux 2023
dnf -y install https://extras.getpagespeed.com/release-latest.rpm
dnf -y install lua5.1-resty-jump-consistent-hash
要在NGINX中使用此Lua库,请确保已安装nginx-module-lua。
本文档描述了lua-resty-jump-consistent-hash v0.1.4,于2016年5月09日发布。
这是这篇论文的简单实现。
特性
- 小内存占用和快速
- 通过服务器的更新保持一致性
使用方法
-
您可以使用基本的jchash模块进行一致性哈希
local jchash = require "resty.chash.jchash" local buckets = 8 local id = jchash.hash_short_str("random key", buckets) -
或者您可以使用包装模块
resty.chash.server对服务器列表进行一致性哈希local jchash_server = require "resty.chash.server" local my_servers = { { "127.0.0.1", 80, 1}, -- {addr, port, weight} 如果权重为1,可以省略 { "127.0.0.2", 80 }, { "127.0.0.3", 80 } } local cs, err = jchash_server.new(my_servers) local uri = ngx.var.uri local svr = cs:lookup(uri) local addr = svr[1] local port = svr[2] -- 现在您可以使用ngx.balancer进行一些一致性负载均衡 -- 您甚至可以更新服务器列表,并保持一致性,例如: 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) -- 如果服务器是127.0.0.2,则保持不变, -- 因为我们只更新了127.0.0.4。 -- 更重要的是,即使服务器数量发生变化,一致性也得以保持!例如: local my_less_servers = { { "127.0.0.2", 80 }, { "127.0.0.3", 80 } } cs:update_servers(my_less_servers) svr = cs:lookup(uri) -- 如果服务器是127.0.0.2,则保持不变, -- 如果服务器是127.0.0.4,则有50%的概率为 -- 127.0.0.3或127.0.0.4 cs:update_servers(my_new_servers) svr = cs:lookup(uri) -- 如果服务器是127.0.0.2,则有66%的概率保持不变
测试
make test
GitHub
您可以在nginx-module-jump-consistent-hash的GitHub仓库中找到此模块的其他配置提示和文档。