local cjosn = require'cjson' -- 获取请求头 local headers = ngx.req.get_headers() local key = "" if headers ~= niland headers["user-id"] ~= nilthen -- 整理请求key key = "grey_key_prefix:"..headers["user-id"]; end
-- 灰度控制 ngx.header["x-response-switch"] = "origin" local v, ok = ngx.shared["grey_host_dict"]:get(key) ifnot v then -- base_upstream 是外部配置的变量,正常服务 ngx.var.switch_upstream = ngx.var.base_upstream else -- grey_upstream 是外部配置的变量,灰度服务 ngx.header["x-response-switch"] = "grey" ngx.var.switch_upstream = ngx.var.grey_upstream end
-- 重载灰度配置文件 if ngx.var.document_uri == "/reload_grey_file"then local fd = io.open(ngx.var.grey_file, "r") local s = fd:read("*a") fd:close()
-- 输出load file 的内容 ngx.print("load json: ") ngx.say(s) local json = cjosn:new() local tb = json.decode(s) for k, v inpairs(tb) do -- 输出实际加入的灰度信息 ngx.say("kv: "..k.." => "..v) ngx.shared["grey_host_dict"]:safe_set(k, v) end ngx.exit(200) end
local parser = require"redis.parser"-- 引入基础库,解析redis响应 local headers = ngx.req.get_headers() local key = "" if headers ~= niland headers["user-id"] ~= nilthen -- 整理请求key key = "grey_key_prefix:"..headers["user-id"]; end
functionhmget(dict, key) -- 构造内部请求 local res = ngx.location.capture("/redis?query=hmget " .. dict .. " ".. key .."\r\n") local replies = parser.parse_replies(res.body, 1) -- 解析响应结果 for i, reply inipairs(replies) do return reply[1] end end
-- 灰度控制 ngx.header["x-response-switch"] = "origin" local v, ok = hmget("grey_host_dict", key) ifnot v then -- base_upstream 是外部配置的变量,正常服务 ngx.var.switch_upstream = ngx.var.base_upstream else -- grey_upstream 是外部配置的变量,灰度服务 ngx.header["x-response-switch"] = "grey" ngx.var.switch_upstream = ngx.var.grey_upstream end