利用 openresty balancer_by_lua 实现一个简单的 ip_hash upstream 调度

以下基于 OpenResty balancer_by_lua 配置指令, 利用 ngx.crc32_long 根据源地址与目的端口生成hash, 实现一个简单的 ip_hash upstream. 仅供参考 

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;
	}
}

参考:

https://github.com/openresty/lua-nginx-module

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值