openresty 前端開發入門四之Redis篇
阿新 • • 發佈:2018-12-26
這章主要演示怎麼通過lua連線redis,並根據使用者輸入的key從redis獲取value,並返回給使用者
操作redis主要用到了lua-resty-redis庫,程式碼可以在github上找得到
而且上面也有例項程式碼
由於官網給出的例子比較基本,程式碼也比較多,所以我這裡主要介紹一些怎麼封裝一下,簡化我們呼叫的程式碼
lua/redis.lua
local redis = require "resty.redis"
local config = {
host = "127.0.0.1",
port = 6379,
-- pass = "1234" -- redis 密碼,沒有密碼的話,把這行註釋掉
}
local _M = {}
function _M.new(self)
local red = redis:new()
red:set_timeout(1000) -- 1 second
local res = red:connect(config['host'], config['port'])
if not res then
return nil
end
if config['pass'] ~= nil then
res = red:auth(config['pass'])
if not res then
return nil
end
end
red.close = close
return red
end
function close(self)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
if self.subscribed then
return nil, "subscribed state"
end
return sock:setkeepalive(10000 , 50)
end
return _M
其實就是簡單把連線,跟關閉做一個簡單的封裝,隱藏繁瑣的初始化已經連線池細節,只需要呼叫new,就自動就連結了redis,close自動使用連線池
lua/hello.lua
local cjson = require "cjson"
local redis = require "redis"
local req = require "req"
local args = req.getArgs()
local key = args['key']
if key == nil or key == "" then
key = "foo"
end
-- 下面的程式碼跟官方給的基本類似,只是簡化了初始化程式碼,已經關閉的細節,我記得網上看到過一個 是修改官網的程式碼實現,我不太喜歡修改庫的原始碼,除非萬不得已,所以儘量簡單的實現
local red = redis:new()
local value = red:get(key)
red:close()
local data = {
ret = 200,
data = value
}
ngx.say(cjson.encode(data))
即可獲取redis中的key為hello的值,如果沒有key引數,則預設獲取foo的值
ok,到這裡我們已經可以獲取使用者輸入的值,並且從redis中獲取資料,然後返回json資料了,已經可以開發一些簡單的介面了
示例程式碼 參見demo4部分