基於 OpenResty balancer_by_lua 配置指令, 利用 ngx.crc32_long 根據源地址與目的端口生成hash, 實現一個簡單的 ip_hash upstream. 僅供參考 nginx
upstream backend{ server 0.0.0.0; balancer_by_lua_block { local balancer = require "ngx.balancer" local host = {"192.168.1.111", "192.168.1.112"} local backend = "" local port = ngx.var.server_port local remote_ip = ngx.var.remote_addr local key = remote_ip..port local hash = ngx.crc32_long(key); hash = (hash % 2) + 1 backend = host[hash] ngx.log(ngx.DEBUG, "ip_hash=", ngx.var.remote_addr, " hash=", hash, " up=", backend, ":", port) local ok, err = balancer.set_current_peer(backend, port) if not ok then ngx.log(ngx.ERR, "failed to set the current peer: ", err) return ngx.exit(500) end ngx.log(ngx.DEBUG, "current peer ", backend, ":", port) } } server { listen 80; listen 8080; listen 7777; server_name *.x.com location / { proxy_pass http://backend; } }
例子2:git
http { upstream backend { server 0.0.0.1; # just an invalid address as a place holder balancer_by_lua_block { local balancer = require "ngx.balancer" -- well, usually we calculate the peer's host and port -- according to some balancing policies instead of using -- hard-coded values like below local host = "127.0.0.2" local port = 8080 local ok, err = balancer.set_current_peer(host, port) if not ok then ngx.log(ngx.ERR, "failed to set the current peer: ", err) return ngx.exit(500) end } keepalive 10; # connection pool } server { # this is the real entry point listen 80; location / { # make use of the upstream named "backend" defined above: proxy_pass http://backend/fake; } } server { # this server is just for mocking up a backend peer here... listen 127.0.0.2:8080; location = /fake { echo "this is the fake backend peer..."; } } }
參考:https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/balancer.mdgithub
https://github.com/openresty/lua-resty-balancerui
https://github.com/openrestythis
https://www.nginx.com/resources/wiki/modules/lua/lua
https://github.com/openresty/lua-nginx-modulespa