openresty + lua 二、openresty 链接 redis,实现 crud

  redis 的话,openresty 已经集成,ng 的话,本身引入便可。html

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

  github 里提供有详细的教程,按照教程来应该是不会有问题的。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 配置:dom

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,搞定。接下来打开浏览器验证一下吧。socket

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

相关文章
相关标签/搜索