# you do not need the following line if you are using # the ngx_openresty bundle: lua_package_path"/path/to/lua-resty-redis/lib/?.lua;;";
server { location /usescript { content_by_lua_block { local redis = require "resty.redis" local red = redis:new()
red:set_timeout(1000) -- 1 sec
-- or connect to a unix domain socket file listened -- by a redis server: -- local ok, err = red:connect("unix:/path/to/redis.sock")
local ok, err = red:connect("127.0.0.1", 6379) if not ok then ngx.say("failed to connect: ", err) return end
--- use scripts in eval cmd local id = "1" ok, err = red:eval([[ local info = redis.call('get', KEYS[1]) info = json.decode(info) local g_id = info.gid
local g_info = redis.call('get', g_id) return g_info ]], 1, id)
if not ok then ngx.say("failed to get the group info: ", err) return end
-- put it into the connection pool of size 100, -- with 10 seconds max idle time local ok, err = red:set_keepalive(10000, 100) if not ok then ngx.say("failed to set keepalive: ", err) return end
-- or just close the connection right away: -- local ok, err = red:close() -- if not ok then -- ngx.say("failed to close: ", err) -- return -- end } } }
从上面的例子可以看到,我们要根据一个对象的 id 来查询该 id 所属 gourp 的信息时,我们的第一个命令是从 Redis 中读取 id 为 1 (id 的值可以通过参数的方式传递到 script 中)的对象的信息(由于这些信息一般 json 格式存在 Redis 中,因此我们要做一个解码操作,将 info 转换成 Lua 对象)。然后提取信息中的 groupid 字段,以 groupid 作为 key 查询 groupinfo。这样我们就可以把两个 get 放到一个 TCP 请求中,做到减少 TCP 请求数量,减少网络延时的效果啦。