我用lua来实现了动态更新proxy后端服务器地址。
local backend_map = ngx.shared.backend_map
local config_json = '{"version":10012,"host":"dev.store.net","origin":"1.1.1.1","origin_schema":"default","ssl":"auto","anti_cc":{"trigger":"default","model":"dynamic"},"blacklist":["1.1.1.1","2.2.2.2"],"whitelist":["127.0.0.1"],"rate_limiting":[]}'
cjson = require "cjson"
config = cjson.decode(config_json)
local succ, err = backend_map:set(config['host'], config_json)
然后用set_by_lua 来设置后端变量
local backend_map = ngx.shared.backend_map
local config_json, err = backend_map:get(ngx.var.host)
if not config_json then
ngx.log(ngx.ERR, "failed to get backend server for host: " ..ngx.var.host, "get backend server: ",err)
return ""
end
cjson = require "cjson"
config = cjson.decode(config_json)
return config['origin']
set $backend "";
set_by_lua_file $backend /usr/local/openresty/nginx/conf/vhost/set_backend.lua;
if ($backend = ""){
return 502;
}
proxy_pass $scheme://$backend;
这样一来这个
set_by_lua_file $backend 是不是每一个请求都要set一次,因为这个set里调用了cjson decode。这样性能可能会是一个大问题。
通过一个api post来动态更新后端的代码。
backend_map = ngx.shared.backend_map
cjson = require "cjson"
local say = ngx.say
function Json_response(status,data)
local response = {}
response['success'] = status
if status then
response['error'] = ""
response['result'] = data
else
response['error'] = data
response['result'] = ""
end
say(cjson.encode(response))
ngx.exit(ngx.OK)
end
function update_config(host,config)
local succ, err = backend_map:set(host, config)
if not succ then
Json_response(false,"update configuration failed: " ..err)
else
local data = {}
data['host'] = host
Json_response(true,data)
end
end
if ngx.var.uri == "/api/update_config" and ngx.var.request_method == "POST" then
ngx.req.read_body()
local data = cjson.decode(ngx.var.request_body)
if data['host'] and data['config'] then
update_config(data['host'], data['config'])
else
Json_response(false,"parameter is incorrect")
end
end