基于 Consul 的模块配置中心
解读
在国内游戏、网关、IoT 等场景里,Lua 常被嵌入到 C/C++ 主程序中做热更逻辑。随着微服务化,运维侧普遍用 Consul 做服务注册与 KV 存储,于是“把 Consul 当远程配置中心,让 Lua 进程无重启地拉取/监听配置”就成了高频面试题。
面试官想确认三件事:
- 你知不知道 Consul 的 KV 模型、长轮询机制及 ACL 鉴权;
- 你能否在 Lua 侧封装“非阻塞、可重试、可降级”的客户端,并与 skynet/OpenResty/Nginx 协程生态结合;
- 你能否把配置映射为 Lua 模块,做到“热更新、无锁、无内存泄漏”,并给出回滚、灰度、容灾方案。
知识点
- Consul REST KV 接口:recurse、raw、?recurse&index=xx 长轮询阻塞 5 min;
- OpenResty cosocket 或 skynet socketchannel,必须保证非阻塞;
- 缓存三件套:worker-level LRU、shared-dict、文件兜底;
- Lua 模块热替换:package.loaded 清理、require 重入、metatable 保护;
- 协程事件分发:ngx.timer.every、skynet.fork,避免每请求新建协程;
- 安全:ACL token 放加密文件、周期刷新、支持国密 SM4 可选;
- 容灾:Consul 集群挂掉时自动降级到本地 snapshot,启动顺序“本地→远程→失败告警”;
- 观测:prometheus 埋点 consul_last_sync_timestamp、config_reload_total、config_version;
- 灰度:在 key 路径里带 appid&grayid,Lua 侧按 worker_id 取模;
- 性能:单次拉取不超过 64 KB,采用 gzip 压缩,index diff 机制减少 90% 流量。
答案
下面给出一套可直接落地的 Lua 伪代码,基于 OpenResty,但同样适用于 skynet(把 ngx 换成 socketchannel 即可)。
- 初始化
-- config_consul.lua
local http = require "resty.http"
local cjson = require "cjson.safe"
local lrucache = require "resty.lrucache"
local lock = require "resty.lock"
local _M = { _VERSION = "0.1" }
local mt = { __index = _M }
local CACHE_VER = 0
local CACHE_TTL = 30 -- 兜底 30s 刷新
local CONSUL_INDEX = 0
local CONSUL_HOST = "http://consul.service.consul:8500"
local CONSUL_KV_PREFIX = "gamesvr/config/"
local ACL_TOKEN = os.getenv("CONSUL_ACL_TOKEN") or ""
local lrucache_obj, err = lrucache.new(500) -- worker 级缓存
if not lrucache_obj then error(err) end
local function consul_get(key, index)
local httpc = http.new()
httpc:set_timeout(5000)
local path = "/v1/kv/" .. CONSUL_KV_PREFIX .. key
local query = { recurse = true, index = index, wait = "300s" }
local headers = { ["X-Consul-Token"] = ACL_TOKEN }
local res, err = httpc:request_uri(CONSUL_HOST..path, {
method = "GET", query = query, headers = headers
})
if not res then return nil, err end
if res.status == 404 then return {}, nil end
if res.status ~= 200 then return nil, "consul code:"..res.status end
local body = cjson.decode(res.body)
if not body then return nil, "invalid json" end
local data = {}
for _, item in ipairs(body) do
local k = item.Key:sub(#CONSUL_KV_PREFIX+1)
data[k] = item.Value and ngx.decode_base64(item.Value) or item.Value
end
return data, nil, tonumber(res.header["X-Consul-Index"])
end
- 长轮询协程
local function watcher(premature, self)
if premature then return end
local new_index = CONSUL_INDEX
local data, err, index = consul_get("", CONSUL_INDEX)
if data then
if index ~= CONSUL_INDEX then
local lock_obj = lock:new("config_lock", {timeout=0.1})
local elapsed, err = lock_obj:lock("reload")
if elapsed then
lrucache_obj:set("config", data, CACHE_TTL)
CACHE_VER = CACHE_VER + 1
CONSUL_INDEX = index
lock_obj:unlock()
ngx.log(ngx.INFO, "config reloaded, ver=", CACHE_VER)
end
end
else
ngx.log(ngx.ERR, "consul watcher fail: ", err)
end
local ok, err = ngx.timer.every(1, watcher, self)
if not ok then ngx.log(ngx.ERR, "timer err:", err) end
end
- 对外接口
function _M.get(key)
local data = lrucache_obj:get("config")
if not data then
-- 极端情况兜底本地文件
local content = io.open("conf/snapshot.json"):read("*a")
data = cjson.decode(content) or {}
lrucache_obj:set("config", data, CACHE_TTL)
end
return data[key]
end
function _M.version() return CACHE_VER end
function _M.init()
local ok, err = ngx.timer.every(1, watcher, _M)
if not ok then error(err) end
end
- 模块热更新
-- 在 init_worker_by_lua 里
local config_center = require "config_consul"
config_center.init()
-- 业务代码随时
local rate_limit = config_center.get("rate_limit")
-
灰度与回滚
在 Consul 里写两份配置:
gamesvr/config/rate_limit和gamesvr/config/rate_limit_gray_1
Lua 侧根据 server_id 取模决定拉哪份,回滚只需把正式 key 覆盖即可。 -
容灾
Consul 失联超过 3 次,把最后一次成功数据写 snapshot.json,进程重启先读本地文件,再后台恢复长轮询。
拓展思考
- 如果配置大于 1 MB,Consul 单值会超时,可把大配置拆成多 key 并用 mget 并行拉取,或改用 Consul Connect + gRPC 流式推送。
- 在 skynet 里,没有 ngx.timer,可以用 skynet.fork + socketchannel 实现相同逻辑,但要自己处理“服务重启后配置漂移”问题,可引入 raft cluster 做配置一致性校验。
- 国内金融级场景需要国密,可把 ACL token 换成 SM4 加密存储,传输走 https + 国密套件,Lua 侧用 luagmssl 解密。
- 配置中心一旦成为 P0 链路,需双 AZ 部署 Consul 集群,并在 Lua 侧实现“多集群选主”:优先同机房,延迟>50 ms 自动切换,切换过程保证 version 单调递增。
- 未来演进:把配置直接编译成 Lua chunk 下发,做到“配置即代码”,利用 LuaJIT 的 trace 记录让热更新路径也能被 JIT,提高 10% 以上性能。