openresty + lua 2、openresty 连接 redis,实现 crud

  redis 的话,openresty 已经集成,ng 的话,自己引入即可。

  github 地址:https://github.com/openresty/lua-resty-redis

  github 里提供有详细的教程,按照教程来应该是不会有问题的。redis 我也简单写了一个工具类,具体贴上我的一系列代码吧.大神勿喷.

 

  工具类:(很基础,重点是自己去写,只是针对初学者,大神忽视即可)

local connectRedisUtil = {}

local redis = require "resty.redis"
-- or connect to a unix domain socket file listened
-- by a redis server:
--     local ok, err = red:connect("unix:/path/to/redis.sock")

function connectRedisUtil.connectRedis() 
    local red = redis:new()
    red:set_timeout(1000) -- 1 sec

    local ok, err = red:connect("127.0.0.1", 6379)
    if not ok then
        ngx.say("failed to connect: ", err)
        return false
    end
    
    return red
end

return connectRedisUtil
View Code

 

  调用:

local connectRedisUtil = require("connectRedisUtil")
local red = connectRedisUtil.connectRedis()
if red == false then
    ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
    return
end

--set
local ok, err = red:set("englishName", "Allen")
if not ok then
    ngx.say("set bad result:", err)
    return
end

--get
local res, err = red:get("englishName")
if not res then
    ngx.say("get englishName failed:", err)
    return
end
ngx.say("englishName is : ", res)

res, err = red:get("name")
if not res then
    ngx.say("get bad result:", err)
    return
else
    ngx.say("res is :", res)
end
View Code

 

  openresty 配置:

server {
    listen 6688;
    server_name localhost;    
    default_type "text/html";

    lua_need_request_body on;

    location = /test_redis_exercise {
        content_by_lua_file /Users/zhuzi/zhuzi_relation/exercise/lua_pro/redis_exercise.lua;
    }
}
View Code

  
  OK,搞定。接下来打开浏览器验证一下吧。

  效果我就不贴了,肯定是没有问题的。今天的就到这里了。

posted @ 2017-11-22 16:59  竹子91  阅读(1477)  评论(0编辑  收藏  举报