nginx+lua(openresty)根据参数转发请求
lua脚本内容:
--解析请求数据的json
local cjson = require 'cjson'
--http转发
local https = require 'resty.http'
--服务器一
local server_one_url = 'http://192.168.1.2:8010/calc'
--服务器二
local server_two_url = 'http://192.168.1.2:8010/calc'
--http post 请求方法
local function http_post(url, data)
local http = https:new()
-- 设置请求的超时时间
http:set_timeouts(600000, 600000, 600000)
local res, err = http:request_uri(url, {
method = 'POST',
body = data,
headers = {
['Content-Type'] = 'application/json';
},
-- 设置关闭keepalive
keepalive = false,
keepalive_timeout = 1,
keepalive_pool = 1000
})
--这里一定要做 and 校验
if res and res.status == 200 then
ngx.say(res.body)
else
-- 设置请求的状态
ngx.status = res.status
-- 设置返回的内容
ngx.say("服务器异常")
end
end
--请求方式
local request_method = ngx.var.request_method
local arg=nil
if request_method == "GET" then
arg = ngx.req.get_uri_args()
elseif request_method == "POST" then
ngx.req.read_body()
arg = ngx.req.get_post_args()
end
ngx.req.read_body()
--请求的参数
local data = ngx.req.get_body_data()
--解析参数
local json = cjson.decode(data)
for k,v in pairs(json) do
ngx.say("参数输出--")
ngx.say(k..":"..v)
end
local windTurbineId = json["windTurbineId"]
ngx.say("获取到的机组id:",windTurbineId)
if (windTurbineId ~= nil and string.match(windTurbineId, "HD170" )~= nil) then
http_post(server_one_url, data)
else
http_post(server_two_url, data)
end
nginx.conf内容:
events {
worker_connections 1024;
}
http {
server {
listen 5002;
# 日志目录配置及日志的级别
error_log logs/error.log debug;
# 设置代理请求的超时时间
proxy_send_timeout 1800s;
server_name localhost;
# 解决lua tcp socket read timed out的异常问题
lua_socket_log_errors off;
location /calc {
content_by_lua_file "item.lua";
}
}
}
注意:这里发起http请求加入了lua-resty-http模块,需要先从git仓库(https://github.com/ledgetech/lua-resty-http/tree/master/lib/resty)将依赖下载下来后,放入t/usr/local/openresty/lualib/resty下。