Hi, Mingxing
你想要的应该是类似thread local的一个东西
但ngx_lua是运行在同一个线程里的, 你可以参考它实现一个requestlocal
大概长这样:
-- requestlocal.lua
local _M = {
instances = { },
}
function _M.getinstance(id)
id = id or tostring(coroutine.running())
if not _M.instances[id] then
local inst = setmetatable({id = id}, {__index = _M})
_M.instances[id] = inst
end
return _M.instances[id]
end
function _M:release()
_M[self.id] = nil
end
return _M
-- index.lua
local requestlocal = require("requestlocal"
local rl1 = requestlocal.getinstance()
local rl2 = requestlocal.getinstance(request_id)
rl:release()
----
如果你在主coroutine里调用getinstance(), 这个request_id参数可以省掉的, 如果在子coroutine里调用, 则需显式传送request_id.
没找到其它更好的标识, 这里我是用处理http请求的主coroutine作为请求标识的.
Best regards
On Thursday, July 30, 2015 at 10:37:56 AM UTC+8, Lance Li wrote:
2015-07-29 21:22 GMT+08:00 Mingxing Zheng
<micke...@gmail.com>:
您没理解我的意思,可能我表述得不够清楚. 我不想要data sharing,相反,我想要一个静态变量,
而且每个请求之间都互不影响.这是data sharing使得请求间互不影响成为不可能. 我想实现的就是Singelton设计模式. 目前我能想到的办法就是全局变量, 毕竟全局变量对于每个请求来说都是唯一的, 但使用全局变量又会污染整个作用域空间
在 2015年7月29日星期三 UTC+8下午6:48:20,YuanSheng Wang写道:
-- mydata.lua
local _M = {}
local data = "">
dog = 3,
cat = 4,
pig = 5,
}
function _M.get_age(name)
return data[name]
end
function _M.set_age(name, age)
data[name] = age
end
return _M
-- test.lua
local mydata = require "mydata"
print("org :", mydata.get_age("cat"))
mydata.set_age("cat", 3)
print("change 1:", mydata.get_age("cat"))
local mydata = require "mydata"
print("cur 1:", mydata.get_age("cat"))
mydata.set_age("cat", 5)
print("change 2:", mydata.get_age("cat"))
2015-07-29 17:27 GMT+08:00 Mingxing Zheng
<micke...@gmail.com>:
这样看起来并不是一个单例, 每次返回的都是一个新构造的table, 例如我的需求是在一次请求中,无论在哪个模块中,
无论跟redis交互几次,都用同一个连接. 这一般都会用到单例
在 2015年7月29日星期三 UTC+8下午5:20:35,doujiang写道:hi,
一般这么玩,详细的可以参考 lua-resty-redis [1],毕竟我们总希望每个 redis 链接实例 都是相互独立的
多看点 lua-resty-* 源码,很有益处,哈哈
local mt = { __index = _M }
function _M.getinstance()
local m = {}
return setmetatable(m, mt)
end
在 2015年7月29日 下午5:05,Mingxing Zheng
<micke...@gmail.com>写道:
恩,在cache开启的情况下, require一个model只会加载一次... 那如果要实现我这个单例的需求,而不希望请求之间相互影响, 应该怎么做??
在 2015年7月29日星期三 UTC+8下午4:18:38,Lance Li写道:
2015-07-29 15:50 GMT+08:00 Mingxing Zheng <micke...@gmail.com>:
Hi,
我需要在我的代码中实现单例, 于是写了个简单的测试代码:
singleton.lua文件:
local _M = {}
local ngx=ngx
function _M.getinstance()
if _M.instance == nil then
ngx.say('new one')
_M.instance = 1
end
return _M.instance
end
return _M
然后在index.lua中调用它, index.lua
local a = require ("singleton")
a.getinstance()
nginx配置使用content_by_lua_file, 然后
为什么在lua_code_cache关闭的情况下,
运行的结果是每次请求都输出new one(这是我期望的结果), 而打开code cache时, 却只有第一次请求输出了new one,后续请求都是无输出??
--
--