Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | 51CTO学院 | CSDN程序员研修院 | OSChina 博客 | 腾讯云社区 | 阿里云栖社区 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏多维度架构

2.4. Redis

nginx 配置

        
location /redis {
default_type 'text/html';  
lua_code_cache on;  
content_by_lua_file lua/redis.lua;
}		
    
    

lua/redis.lua 程序

        
[root@netkiller nginx]# cat lua/redis.lua 
local host = "127.0.0.1"  
local port = 6379  
-- local password = "passw0rd"
local password = ""
local redis = require("resty.redis")  
local conn = redis:new()  

conn:set_timeout(5000)  

local ok, err = conn:connect(host, port)

if not ok then
ngx.say("connect to redis error : ", err)
return 
elseif password and password ~= "" then
ok, err = conn:auth(password)
if not ok then
    ngx.say("failed to authenticate: ", err)
    return 
end
end

ok, err = conn:set("msg", "hello world")
if not ok then
ngx.say("set msg error : ", err)
end

local value, err = conn:get("msg")
if not value then
ngx.say("get msg error : ", err)
end
if value == ngx.null then  
value = ''  
end

ngx.say("msg : ", value)  

local ok, err = conn:close()
if not ok then
ngx.say("close redis error:", err)
end
    
    

list

        
local lists, err = red:lrange("nokey", 0, -1)
ngx.say(lists)		
    
    

set

        
red:sadd("city","Shenzhen","Shanghai","Beijing")
local citys, err = red:smembers("city")
ngx.say(citys)

for i, item in ipairs(citys) do
ngx.say(item)
end