Consul/Nacos 长轮询实现热更新

解读

国内游戏、金融、IoT 项目普遍把 Consul 或 Nacos 当作“分布式配置中心”。Lua 侧的热更新诉求是:进程不重启、不中断玩家逻辑,就能把新配置(掉落表、活动开关、灰度规则)秒级生效。
面试官问“长轮询实现热更新”,重点不在“长轮询”原理,而在“Lua 运行时如何零停机、零竞态、低 GC 地把远端配置同步进来”。他希望你把网络、序列化、并发、版本控制、回滚、观测性都说圆,并给出可直接落地的 Lua 代码骨架。

知识点

  1. Consul/Nacos 阻塞查询机制
    • Consul:带 index 的 HTTP 阻塞查询,30 s 超时,返回 304 表示无变更。
    • Nacos:/nacos/v1/cs/configs/listener 长轮询,30 s 超时,返回空数组表示无变更。
  2. Lua 协程 + 非阻塞 I/O
    skynet、OpenResty、Kong、TVM 均用协程实现单线程并发,避免回调地狱。
  3. 原子替换与双缓冲
    配置表用“指针交换”实现原子生效,读逻辑全程无锁;老表延迟 GC。
  4. 版本号与一致性校验
    远端返回的 ModifyIndex 或 md5 作为版本号,本地先校验再 swap,防止半包。
  5. 容灾三板斧
    本地快照、回滚、熔断。
  6. 观测性
    Prometheus 埋点:拉取耗时、版本号、失败次数、热更新延迟。

答案

下面以 OpenResty 环境 + Consul 为例,给出可直接落地的长轮询热更新模块(Nacos 只需把 URL 和鉴权头换掉即可)。代码全部单文件,无外部依赖,保持 100 行以内,方便面试手撕。

-- config_hotreload.lua
local http = require "resty.http"
local cjson = require "cjson.safe"
local ngx_now = ngx.now
local ngx_log = ngx.log
local INFO = ngx.INFO
local ERR = ngx.ERR

local _M = { _VERSION = "0.1" }

-- 配置缓存:双重缓冲
local config_cache = {}
local config_version = 0

-- 本地快照文件,Consul 不可用时兜底
local snapshot_file = ngx.config.prefix() .. "conf/snapshot.json"

-- 从 Consul 阻塞查询
local function consul_long_poll(index)
    local hc = http:new()
    hc:set_timeout(30000)  -- 阻塞 30 s
    local url = ("http://127.0.0.1:8500/v1/kv/game/config?recurse&wait=30s&index=%d"):format(index)
    local res, err = hc:request_uri(url, { method = "GET" })
    if not res then
        return nil, "http err: " .. (err or "unknown")
    end
    if res.status == 304 then
        return 304, index  -- 无变更
    end
    if res.status ~= 200 then
        return nil, "consul status " .. res.status
    end
    local body = cjson.decode(res.body)
    if not body then
        return nil, "invalid json"
    end
    -- 把 KV 拼成一张大表
    local new_conf = {}
    for _, item in ipairs(body) do
        local key = item.Key:match("^game/config/(.+)$")
        if key then
            local ok, val = pcall(cjson.decode, ngx.decode_base64(item.Value))
            new_conf[key] = ok and val or item.Value
        end
    end
    return new_conf, tonumber(res.header["X-Consul-Index"])
end

-- 原子替换
local function swap_config(new_conf, new_ver)
    -- 深拷贝一层,防止外部持有引用
    local snapshot = cjson.decode(cjson.encode(new_conf))
    config_cache = snapshot
    config_version = new_ver
    -- 写本地快照
    local f, err = io.open(snapshot_file, "w+")
    if f then
        f:write(cjson.encode(snapshot))
        f:close()
    end
    ngx_log(INFO, "config swapped, version=", new_ver)
end

-- 加载本地快照
local function load_snapshot()
    local f, err = io.open(snapshot_file, "r")
    if not f then
        return nil, err
    end
    local content = f:read("*a")
    f:close()
    return cjson.decode(content)
end

-- 对外提供读接口,无锁
function _M.get(key)
    return config_cache[key]
end

-- 后台协程入口
function _M.run()
    ngx.timer.every(0, function(premature)
        if premature then return end
        local index = config_version
        while not ngx.worker.exiting() do
            local new_conf, new_index = consul_long_poll(index)
            if new_conf == 304 then
                -- 无变更,继续阻塞
                index = new_index
            elseif type(new_conf) == "table" then
                -- 有变更,原子替换
                swap_config(new_conf, new_index)
                index = new_index
            else
                ngx_log(ERR, "consul poll err: ", new_index)
                -- 读本地快照兜底
                local snap = load_snapshot()
                if snap then
                    swap_config(snap, index)  -- 版本号保持不变
                end
                ngx.sleep(3)  -- 退避
            end
        end
    end)
end

return _M

使用方式(init_worker_by_lua):

local cfg = require "config_hotreload"
cfg.run()

业务代码随时无锁读取:

local drop = cfg.get("drop_table")

要点回顾

  1. 全程单协程,无轮询风暴,30 s 长阻塞返回才触发一次 GC。
  2. 原子替换:读线程无锁,老表延迟 GC,不会读到半成品。
  3. 本地快照 + 退避重试,Consul 宕机仍可秒级启动。
  4. 版本号用 X-Consul-Index,天然单调递增,可对接 Prometheus 做版本监控。

拓展思考

  1. 大规模节点如何降低 Consul 压力?
    在网关层做“配置聚合层”,Lua 侧只轮询本机 agent cache,或改用 Nacos 的 UDP 推送通道。
  2. 配置灰度怎么做?
    在 Consul KV 里加 gray_percent 字段,Lua 侧按玩家 ID 哈希决定是否使用新表;同时提供 /config/gray 接口实时调比例。
  3. 多进程模型(skynet)如何复用?
    把长轮询放在唯一“配置服”,通过 skynet 消息广播给各逻辑服,避免 N 个进程同时长轮询。
  4. 如何防止“惊群”?
    OpenResty 里用 ngx.worker.id() == 0 限定仅 0 号 worker 拉取,其余 worker 共享内存字典。
  5. 配置回滚策略?
    Consul 存 10 份历史版本,Lua 侧暴露 /config/rollback?index=N 接口,秒级回滚;同时把回滚事件写入日志队列,方便审计。