在 nginx 中结合 lua 实现自定义调度,核心做法是利用 openresty 提供的 balancer_by_lua_block 指令。该指令允许开发者在负载均衡阶段介入,通过调用 balancer.set_current_peer() 动态指定上游服务器地址,从而绕过默认的轮询或哈希逻辑,实现基于业务逻辑(如连接数、健康状态或特定算法)的自定义调度。

如何获取并过滤可用的上游节点
要实现自定义调度,第一步是获取当前配置的所有上游节点列表,并根据业务条件筛选出可用节点。在 Lua 脚本中,可以通过 balancer.get_upstreams() 获取所有已定义的上游组信息,进而解析出具体的服务器 IP 和端口。筛选过程通常涉及检查节点的权重、当前负载或健康状态,最终从候选列表中挑选出一个目标节点。

local balancer = require "ngx.balancer"
-- 模拟获取上游节点列表
local upstreams = balancer.get_upstreams()
local candidates = {}
for _, group in ipairs(upstreams) do
for _, peer in ipairs(group.peers) do
-- 假设我们只选择权重大于0且状态为正常的节点
if peer.weight > 0 and peer.status == "up" then
table.insert(candidates, {
ip = peer.addr,
port = peer.port,
weight = peer.weight
})
end
end
end
-- 简单的加权随机选择示例
if #candidates > 0 then
local total_weight = 0
for _, c in ipairs(candidates) do
total_weight = total_weight + c.weight
end
local random_val = math.random(total_weight)
local current_sum = 0
local selected_peer = nil
for _, c in ipairs(candidates) do
current_sum = current_sum + c.weight
if random_val <= current_sum then
selected_peer = c
break
end
end
if selected_peer then
-- 设置当前请求的目标 peer
local ok, err = balancer.set_current_peer(
selected_peer.ip,
selected_peer.port
)
if not ok then
ngx.log(ngx.ERR, "Failed to set peer: ", err)
return ngx.exit(500)
end
end
end
上述代码展示了如何从上游组中提取节点并进行加权随机选择。关键点在于 balancer.set_current_peer() 的调用,它直接决定了后续请求将被转发到哪个具体的 IP 和端口。如果筛选后的候选列表为空,或者设置 peer 失败,则应返回错误码以终止请求。
如何处理后端故障转移与重试
在自定义调度中,除了选择初始节点,还需要处理节点不可用的情况。当选定的节点响应超时或连接失败时,Lua 脚本可以介入进行故障转移。这通常通过在 balancer_by_lua_block 中捕获错误,或者结合 header_filter_by_lua_block 来检查响应状态,并在必要时重新调用 set_current_peer() 切换到备用节点。

-- 简化的故障转移逻辑示意
local function try_next_peer(candidates, index)
if index > #candidates then
return false, "No more peers available"
end
local peer = candidates[index]
local ok, err = balancer.set_current_peer(peer.ip, peer.port)
if not ok then
return false, err
end
return true, nil
end
-- 在实际使用中,这通常需要在更复杂的上下文中管理状态
-- 例如,记录已尝试的节点,避免循环重试
local tried_peers = {}
-- 假设在某处检测到当前 peer 失败
-- local success, err = try_next_peer(candidates, #tried_peers + 1)
-- if success then
-- table.insert(tried_peers, candidates[#tried_peers])
-- else
-- ngx.exit(502) -- Bad Gateway
-- end
故障转移的实现需要维护一个已尝试节点的列表,以防止无限重试同一个失败的节点。虽然 balancer_by_lua_block 主要作用于请求发起前的阶段,但结合 Nginx 的其他生命周期钩子,可以实现更复杂的重试逻辑。重要的是,每次切换节点后,必须确保新的 peer 被正确设置,并且请求上下文能够正确转发到新节点。
基于连接数的动态权重调整如何实现
为了实现更精细的负载均衡,可以根据后端的实时连接数动态调整调度策略。这需要 Lua 脚本定期收集各节点的活跃连接数,并在 balancer_by_lua_block 中根据这些指标计算新的权重或优先级。连接数较少的节点将获得更高的调度概率,从而实现负载的动态均衡。
具体实现上,可以使用 ngx.shared.DICT 来存储各节点的连接数统计信息。在 balancer_by_lua_block 中,读取最新的连接数数据,并将其转换为调度权重。例如,可以采用反比关系:连接数越少,权重越高。然后,使用加权随机算法选择节点。这种方法能够有效避免将大量请求发送到已经过载的后端服务器,提升系统的整体稳定性和响应速度。


















