来源:https://opm.openresty.org/package/openresty/lua-resty-redis/ 更多 redis 指令可以从这个文档中查到
local ok, err = red:connect("127.0.0.1", 6379)
local res, err = red:get("key")
local res, err = red:lrange("nokey", 0, 1)
local res, err = red:hmget("myhash", "field1", "field2", "nofield")
-
local res, err = red:hmset("myhash", "field1", "Hello", "field2", "World")
-
syntax: red, err = redis:new()
syntax: ok, err = red:connect(host, port, options_table?)
syntax: ok, err = red:connect("unix:/path/to/unix.sock", options_table?)
syntax: red:set_timeout(time)
syntax: ok, err = red:set_keepalive(max_idle_timeout, pool_size)
syntax: times, err = red:get_reused_times()
syntax: ok, err = red:close()
syntax: red:init_pipeline()
syntax: red:init_pipeline(n)
syntax: results, err = red:commit_pipeline()
syntax: red:cancel_pipeline()
syntax: red:hmset(myhash, field1, value1, field2, value2, ...)
syntax: red:hmset(myhash, { field1 = value1, field2 = value2, ... })
syntax: hash = red:array_to_hash(array)
syntax: res, err = red:read_reply()
syntax: hash = redis.add_commands(cmd_name1, cmd_name2, ...)
local res, err = red:auth("foobared")
完整代码
# you do not need the following line if you are using
# the OpenResty bundle:
lua_package_path "/path/to/lua-resty-redis/lib/?.lua;;";
server {
location /test {
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
ok, err = red:set("dog", "an animal")
if not ok then
ngx.say("failed to set dog: ", err)
return
end
ngx.say("set result: ", ok)
local res, err = red:get("dog")
if not res then
ngx.say("failed to get dog: ", err)
return
end
if res == ngx.null then
ngx.say("dog not found.")
return
end
ngx.say("dog: ", res)
red:init_pipeline()
red:set("cat", "Marry")
red:set("horse", "Bob")
red:get("cat")
red:get("horse")
local results, err = red:commit_pipeline()
if not results then
ngx.say("failed to commit the pipelined requests: ", err)
return
end
for i, res in ipairs(results) do
if type(res) == "table" then
if res[1] == false then
ngx.say("failed to run command ", i, ": ", res[2])
else
-- process the table value
end
else
-- process the scalar value
end
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
}
}
}
其中第17行 red:connect("127.0.0.1", 6379)
,如果是容器的域名,可以参考 openresty 解析本地域名 lua-local-resolver