我也有一个类似需求, 写了一个例子, 你看看是否合用
其中 把resty.lock 改成ngx.sleep应该会更好一些,因resty.lock里面也是ngx.sleep
init_worker_by_lua '
transaction = {};
--local tcpsock;
local create_socket = function()
if not tcpsock then
tcpsock =
ngx.socket.tcp();
ngx.log(ngx.WARN,"try connect...");
local ok, err =
tcpsock:connect("10.10.50.115",9013);
if not ok then
ngx.log(ngx.ERR,"fail to connect ",err);
tcpsock = nil;
end;
end;
end;
local lock = require "resty.lock";
local function save(key,value)
local trans_lock =
lock:new("my_locks");
trans_lock:lock(key);
transaction[key]=
{trans_lock};
return;
end;
local timer = function(premature)
ngx.log(ngx.WARN,"recv_loop");
while true do
create_socket();
-- ngx.log(ngx.WARN,"in
timer");
local line, err, partial =
tcpsock:receive()
if not line then
ngx.log(ngx.ERR, "failed to
read a line: ", err);
-- res = string.find(err,".*timed
out");
-- if not res then
--
tcpsock = nil;
-- end;
else
local _,_,k,v = string.find(line, "(%a+)%s*=%s*(%a+)")
ngx.log(ngx.WARN, "KEY IS "..k," VALUE IS "..v);
transaction[k][2]=v.." is set ok";
local ok, err = transaction[k][1]:unlock(k);
if not ok then
ngx.say("failed to unlock: ", err)
end;
end;
end;
end;
local
sendvalue;
local sendloop;
function send_loop()
while true do
if not sendvalue
then
ngx.sleep(0.01);
else
local bytes, err = tcpsock:send(sendvalue);
--key.."="..value
if not bytes
then
ngx.log(ngx.ERR,"send
failed reason is ",err);
else
ngx.log(ngx.WARN, bytes," bytes are sent");
sendvalue = nil;
end;
end;
end;
end;
local sendtimer = function(premature)
create_socket();
ngx.thread.spawn(timer);
send_loop();
end;
function transaction.send(key,value)
ngx.log(ngx.WARN,"in transaction.send");
save(key,value);
sendvalue = key.."="..value;
local lock = require "resty.lock"
local trans_lock = lock:new("my_locks");
local elapsed, err = trans_lock:lock(key);
ngx.say(elapsed, ", ", err);
trans_lock:unlock(key);
local res = transaction[key][2];
transaction[key] = nil;
return
res;
end;
ngx.timer.at(0,sendtimer);
';
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location /linsu {
content_by_lua '
if not transaction then
ngx.say "transaction is nil";
return;
end;
local rsp = transaction.send(ngx.var.arg_key, ngx.var.arg_value);
ngx.say(rsp);
';
}
发件人: openresty@googlegroups.com
[mailto:openresty@googlegroups.com] 代表
shawnf...@gmail.com
发送时间: 2015年5月15日 9:32
收件人:
openresty@googlegroups.com
主题: [openresty] NGINX多个请求能否共用一个长连接
春哥:
你好!我现在需要利用NGINX的反向代理功能与本机的一个进程通讯,因为每个请求过来后,都需要与之通信,所以希望使用一条TCP长连接。但现在了解到的情况是NGINX为每个请求都创建一个独立的连接。
请问在NGINX中能否为多个请求维护和管理一条长连接?
--
--