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部分接口

相关文章
相关标签/搜索