文章出處
文章列表
這章主要演示怎么通過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))
訪問
http://localhost/lua/hello?key=hello
即可獲取redis中的key為hello的值,如果沒有key參數,則默認獲取foo的值
ok,到這里我們已經可以獲取用戶輸入的值,并且從redis中獲取數據,然后返回json數據了,已經可以開發一些簡單的接口了
示例代碼 參見demo4部分
文章列表
全站熱搜
留言列表