lua-redis
worker_processes 1;
error_log logs/error.log;
events {
worker_connections 1024;
}
http {
server {
listen 8080;
location /api {
content_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()
ngx.say(type(red))
--red:set_timeouts(1000, 1000, 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("43.247.184.32",8967)
local res, err = red:auth("Gongsibao2018")
if not ok then
ngx.say("failed to connect: ", err)
return
end
local 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
ngx.say("dog: ", err ~= ngx.null)
if res == ngx.null then
ngx.say("dog not found.")
return
end
ngx.say("dog: ", err)
ngx.say("dog: ", res)
ngx.say("dog: ===============================")
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
ngx.say(res)
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
local res, err = red:hmset("myhash", "field1", "Hello", "field2", "World")
ngx.say(res,err);
local res, err = red:hmget("myhash", "field1", "field2",'nofiled')
ngx.say(res,err);
ngx.say("sub publish..................................................................................................")
local cjson = require "cjson"
local red1 = redis:new()
local red2 = redis:new()
red1:set_timeouts(1000, 1000, 1000) -- 1 sec
red2:set_timeouts(1000, 1000, 1000) -- 1 sec
local ok, err = red1:connect("43.247.184.32",8967)
local res, err = red1:auth("Gongsibao2018")
local ok, err = red2:connect("43.247.184.32",8967)
local res, err = red2:auth("Gongsibao2018")
local res, err = red1:subscribe("dog")
ngx.say("1: subscribe: ", cjson.encode(res))
res, err = red2:publish("dog", "Hello")
ngx.say("2: publish: ", cjson.encode(res))
res, err = red1:read_reply()
ngx.say("1: receive: ", cjson.encode(res))
local ok, err = red2:multi()
local ans, err = red2:set("a", "abc")
ngx.say("set ans: ", cjson.encode(ans))
local ans, err = red2:get("a")
ngx.say("set ans: ", cjson.encode(ans))
ans, err = red2:exec()
ngx.say("exec ans: ", cjson.encode(ans))
}
}
}
}