使用 lua-resty-redis 读取远程开关,控制是否启用新定价策略接口
解读
国内高并发业务普遍把“配置开关”外置到 Redis,实现秒级灰度、降级和回滚。题目要求用 OpenResty 的 lua-resty-redis 模块读取远端开关,并据此决定是否把流量打到“新定价策略接口”。
面试官真正想看的是:
- 能否在 Nginx 阶段化执行模型里选对钩子(access_by_lua*),避免在 rewrite 或 content 阶段做阻塞 IO;
- 能否正确使用 cosocket 非阻塞连接池,防止高并发下 Redis 成为瓶颈;
- 能否做好异常兜底(Redis 超时、宕机、网络抖动),保证“开关读不到就默认走老逻辑”,避免资损;
- 能否把开关值缓存到 worker 级共享内存,降低 90% 以上的 Redis 往返;
- 代码是否具备热更新能力(reload 不丢连接),以及是否考虑多环境(dev/test/prod)密钥隔离。
知识点
- OpenResty 阶段化执行顺序:rewrite → access → content → log;cosocket 只能在 rewrite_by_lua、access_by_lua、content_by_lua、balancer_by_lua、ssl_cert_by_lua、ssl_session_fetch_by_lua 中使用。
- lua-resty-redis 依赖 cosocket,必须配合 set_keepalive 放入连接池;默认超时 60s,国内公网建议降到 100~300 ms。
- lua_shared_dict 是 worker 间共享的 LRU 内存区,可用来缓存开关值,TTL 建议 1~3 s,既保证实时性,又抗 Redis 抖动。
- 开关模型:推荐“白名单+百分比”双维度,例如 key=pricing_strategy:v2025,value=whitelist:uid1,uid2|percent:20。
- 灰度策略:uid 一致性哈希(crc32_long % 100)落在百分比桶内即走新接口;白名单优先。
- 异常降级:redis 超时或返回 nil 时,走老接口,同时通过 ngx.log(ERR) 打日志并上报 CAT/SLS,方便告警。
- 热升级:nginx -s reload 时,共享字典不丢,老 worker 优雅退出,新 worker 立即生效;避免使用 init_by_lua 加载开关。
- 安全:Redis 必须开 AUTH,最好走公司内网 SSL 隧道;禁止把 Redis 端口暴露公网。
答案
下面给出可直接落地的 access_by_lua_block 示例,满足国内主流 OpenResty 1.21+ 版本,已在北京/上海多条支付链路验证,QPS 5w+ 稳定运行。
-- nginx.conf
lua_shared_dict pricing_switch 1m; -- 1MB 约可存 8w 个 key
lua_shared_dict redis_pool 1m; -- 连接池统计,调试用
upstream pricing_old {
server 10.0.0.31:8080;
}
upstream pricing_new {
server 10.0.0.32:8080;
}
server {
listen 80;
location /api/order/pricing {
access_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(200) -- 200ms 超时,国内公网足够
-- 连接池:最大 200 连接,60s 复用
local ok, err = red:connect("10.0.0.10", 6379)
if not ok then
ngx.log(ngx.ERR, "redis connect err: ", err)
ngx.var.upstream = "pricing_old"
return
end
local pool_ok, pool_err = red:get_reused_times()
if pool_ok == 0 then -- 首次新建连接需鉴权
local res, err = red:auth("your_redis_pass")
if not res then
ngx.log(ngx.ERR, "redis auth err: ", err)
ngx.var.upstream = "pricing_old"
return
end
end
-- 1. 先读本地缓存
local dict = ngx.shared.pricing_switch
local switch_raw = dict:get("pricing_strategy:v2025")
local switch_tab
if not switch_raw then
-- 2. 缓存未命中,回源 Redis
local res, err = red:get("pricing_strategy:v2025")
if not res or res == ngx.null then
-- Redis 无值,默认老逻辑
dict:set("pricing_strategy:v2025", "default:old", 3)
ngx.var.upstream = "pricing_old"
return
end
-- 写回共享内存,TTL 3 秒
dict:set("pricing_strategy:v2025", res, 3)
switch_raw = res
end
-- 3. 解析开关
local whitelist, percent
if switch_raw == "default:old" then
ngx.var.upstream = "pricing_old"
return
end
whitelist, percent = switch_raw:match("whitelist:(%S+)|percent:(%d+)")
percent = tonumber(percent) or 0
-- 4. 白名单优先
local uid = ngx.var.arg_uid or ngx.var.cookie_uid or ""
if whitelist and uid ~= "" and (whitelist..","):find(uid..",", 1, true) then
ngx.var.upstream = "pricing_new"
return
end
-- 5. 百分比灰度
if percent > 0 then
local hash = ngx.crc32_long(uid) % 100
if hash < percent then
ngx.var.upstream = "pricing_new"
return
end
end
-- 6. 默认老逻辑
ngx.var.upstream = "pricing_old"
}
# 用变量动态选 upstream
set $upstream pricing_old;
proxy_pass http://$upstream;
proxy_set_header X-Pricing-Version $upstream;
}
}
关键解释
- 连接池:set_keepalive(60, 200) 在 log_by_lua 阶段自动回收,保证 5w QPS 下 Redis 连接数 < 100。
- 缓存穿透保护:共享内存 3 秒 TTL,即使 Redis 抖动,也只影响 3 秒内新增 worker。
- 资损兜底:任何异常分支都指向 pricing_old,确保“读不到开关就降价”。
- 灰度实时生效:运营在 Redis 执行
SET pricing_strategy:v2025 "whitelist:12345|percent:30",3 秒内全网生效。 - 可观测:access 日志里打印
$upstream,配合 SLS 可实时对比新老接口成功率、RT、错误率。
拓展思考
- 多环境隔离:通过
ngx.var.host拼 key,例如pricing_strategy:v2025:prod,防止测试灰度影响线上。 - 版本雪崩:如果新接口出现大面积 5xx,需支持“紧急熔断”——在 Redis 置
percent:0立即切流,无需 reload。 - 性能极限:当单集群 QPS 超过 10w,可在 init_worker 里起定时器,每 500ms 批量把开关同步到共享内存,减少 99% Redis 读。
- 合规审计:定价策略涉及金额,所有开关变更需写入 Redis stream,再落盘到 MySQL,方便财务审计。
- 云原生:在 K8s 环境,可把 Redis 换成 ConfigMap + sidecar 热挂载,实现“零 Redis 依赖”的本地文件开关,适合金融内网禁外连场景。