Hi,
请教一个小白问题
我在用openresty作为基于HTTP的API Server,现在想改为基于TCP的长连接,但是保持原来Http的API。
目前,我是这么做的:
1. 引入stream-lua-nginx-module和lua-resty-http
2. nginx.conf里添加stream:
stream {
# define a TCP server listening on the port 1234:
server {
listen 1234;
content_by_lua_file /opt/openresty/nginx/lua/stream.lua;
}
}
3. stream.lua里监听接口,并将接收到的信息作为参数,通过lua-resty-http请求原http的接口:
local cjson = require "cjson.safe”
--判断table里面是否包含某些element的函数
local function tableContains(table, element)
if not table then
return false
end for key, value in pairs(table) do
if key == element then
return true
end
end
return false
end
function handleSocket()
--建立socket
local tcp_req,err = ngx.req.socket(true)
if not tcp_req then
ngx.log(ngx.ERR,"--->get req socket err:",err)
end
--开启监听,如果包含key为’body’的参数,则为有效包,其他为心跳包等
while true do
local req_data
req,err = tcp_req:receive()
if not req then
ngx.log(ngx.ERR,"--->get req_data err:",err,"\n”)
return
end
local jsonResp = req
local req_data = cjson.decode(req)
local param
if tableContains(req_data,"body") then
local body = req_data["body”]
local body_data
if body then
body_data = cjson.decode(body)
else
return false
end
if tableContains(body_data,"param”) then
param = body_data["param”]
end
end
-- send HTTP request,该param为之前http的参数
if param ~= nil then
local http = require "resty.http”
local httpc = http.new()
local response, err
response, err = httpc:request_uri("http://example.cn"..param)
if not response then
ngx.log(ngx.ERR,"#####--->failed to request: ",err)
return
else
resp= {value = response.body};
tcp_req:send(cjson.encode(resp))
tcp_req:send("\r\n”)
ngx.log(ngx.ERR,"#####--->response:",cjson.encode(resp)," #####\n”)
end
else
tcp_req:send(jsonResp)
tcp_req:send("\r\n”)
end
end
end
handleSocket()
有两个问题:
1.这种方式,会报error:no lua_resolver defined to resolve "example.cn " while handling client connection
2.请问这么做是否合理?