nginx用lua脚本读取redis(脚本篇)

1.目的

     实现生成随机的key,从redis中取出该key的值(string类型和hash类型)

2.配置nginx

lua_package_path "/usr/local/lua/?.lua;;";     //在http中增加

location /test {  
			default_type 'text/plain';
			content_by_lua_file /usr/local/luascript/radmstr.lua;  
		} 

3.lua脚本(string类型)

local redis = require "resty.redis"  
local json = require "json"

--connect  
local cache = redis.new()  
  
local ok, err = cache.connect(cache, '127.0.0.1', '6379')  
  
cache:set_timeout(1000)  
  
if not ok then  
        ngx.say("failed to connect:", err)  
        return  
end  

--random num
local radmnum=math.random(0, 10000000)            --生成随机数
local radmkey="BASE:USER:STRING.U"..radmnum       --根据存放key的规则
ngx.say("radmkey is:",radmkey)

--get 
local res, err = cache:get(radmkey)  
if not res then  
        ngx.say("failed to get key:",radmkey, err)  
        return  
end  
  
if res == ngx.null then  
        ngx.say(radmkey," not found.")  
        return  
end  
   
value = json.encode(res)
ngx.say(value)

--close  
local ok, err = cache:close()  
  
if not ok then  
        ngx.say("failed to close:", err)  
        return  
end 
4.lua脚本(hash类型)

--前面连接和关闭代码同string类型,不重复写了

--random num
local radmnum=math.random(0, 10000000)
local radmkey="BASE:USER:HASH.U"..radmnum
ngx.say("radmkey is:",radmkey)

--hgetall
local res, err = cache:hgetall(radmkey)  
if not res then  
        ngx.say("failed to get key:",radmkey,err)  
        return  
end  
  
if res == ngx.null then  
        ngx.say(radmkey," not found.")  
        return  
end  

value = json.encode(res)
ngx.say(value)
5.测试

访问:curl http://localhost/test



你可能感兴趣的:(redis,nginx,lua)