openresty 前端開發入門四之Redis篇

這章主要演示怎麼經過lua鏈接redis,並根據用戶輸入的key從redis獲取value,並返回給用戶

操做redis主要用到了lua-resty-redis庫,代碼能夠在github上找獲得git

並且上面也有實例代碼github

因爲官網給出的例子比較基本,代碼也比較多,因此我這裏主要介紹一些怎麼封裝一下,簡化咱們調用的代碼web

lua/redis.luaredis

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自動使用鏈接池json

lua/hello.luaui

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?ke...lua

便可獲取redis中的key爲hello的值,若是沒有key參數,則默認獲取foo的值rest

ok,到這裏咱們已經能夠獲取用戶輸入的值,而且從redis中獲取數據,而後返回json數據了,已經能夠開發一些簡單的接口了code

示例代碼 參見demo4部分接口

相關文章
相關標籤/搜索