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下。
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值