I'm trying to learn how to use balancer_by_lua using
https://github.com/agentzh/lua-resty-balancer as an example. My find() function works in the init_by_lua block and I can see it rotating through the four IPs I have configured with no problem. However, when I call the find() function in the balancer_by_lua block, I always get the same address because self.last_id never updates - as-if I'm working on a copy of "self" in the find function and my changes to it are being lost. I don't see where lua-resty-balancer is doing anything special in its balancer block, so I'm not sure what is going wrong and could use some help. What I am looking for is the find function in balancer_by_lua_block to return a different value every time.
Here is my nginx.conf:
--------
user nginx;
worker_processes 24;
worker_rlimit_nofile 8192;
pid /var/run/nginx.pid;
events {
worker_connections 8192;
}
http {
error_log /var/log/nginx/error.log debug;
lua_code_cache off;
lua_package_path '/etc/nginx/?.lua;;';
init_by_lua_block {
local xxtest = require "baltest"
local test1 = xxtest:new(nil)
for i=1,10 do
ngx.log(ngx.NOTICE, "TEST" .. i .. ": " .. test1:find())
end
package.loaded.my_test1 = test1
}
upstream foo {
server 0.0.0.1;
balancer_by_lua_block {
local b = require "ngx.balancer"
local test1 = package.loaded.my_test1
local res = test1:find()
ngx.log(ngx.NOTICE, "PEER: " .. res)
assert(b.set_current_peer(res, 80))
}
}
server {
listen 9080;
server_name "_";
location / {
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_buffering off;
}
}
}
--------
And here is my baltest.lua where I am trying to create a class like lua-resty-balancer does:
--------
local next = next
local setmetatable = setmetatable
local _M = {}
local mt = { __index = _M }
function _M.new(_)
local newnodes = { "192.168.128.1", "192.168.128.2", "192.168.128.3", "192.168.128.4" }
local self = {
nodes = newnodes, -- it's safer to copy one
last_id = nil,
}
return setmetatable(self, mt)
end
local function _find(self)
local nodes = self.nodes
local last_id = self.last_id
id = next(nodes, last_id)
if (id == nil) then
id = next(nodes, nil)
end
self.last_id = id
return nodes[id]
end
_M.find = _find
return _M
--------