一、OpenResty的lua訪問redis的插件:https://github.com/openresty/lua-resty-redis前端
下載後,導入對應的插件:lua_package_path "D:/work/openresty-1.13.6.1-win32/lua-resty-redis/lib/resty/?.lua;;";nginx
二、使用lua訪問redis:git
server {
location /test {
content_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()github
red:set_timeout(1000) -- 1 secredis
-- 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
enddom
ok, err = red:set("dog", "an animal")
if not ok then
ngx.say("failed to set dog: ", err)
return
endsocket
ngx.say("set result: ", ok)ui
local res, err = red:get("dog")
if not res then
ngx.say("failed to get dog: ", err)
return
endlua
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
}
}
}
三、使用redis鏈接池
local ok, err = red:set_keepalive(60000, 20)
四、須要密碼的redis的訪問:使用 auth 方法
local ok, err = red.connect(red, "127.0.0.1", "6379")
if not ok then
return
end
local res, err = red:auth("password")
if not res then
return
end
五、redis的操做,不須要單獨封裝方法,lua-resty-redis 支持自動生成對應的lua方法
具體配置方法是:redis.lua 中,common_cmds 的array,在這裏添加須要使用的方法
例如:須要使用redis hsah的hincrby,那麼就在 common_cmds 添加 hincrby,在lua中直接使用就能夠,red:hincrby(key, field, 1)
六、項目中的使用場景
(1)前端http查詢一些數據,直接在nginx中經過lua訪問redis拿到,直接返回到前端,減小服務器的壓力;redis中數據經過服務器進行主動更新
(2)點擊次數和頁面打開次數分析:在點擊和頁面打開之間,加上了請求到達nginx的統計,當請求到達nginx時,經過lua將訪問的頁面次數寫入redis中,而後經過點擊次數、nginx得到的請求次數、頁面打開次數進行具體業務的分析