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
調用:瀏覽器
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
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; } }
OK,搞定。接下來打開瀏覽器驗證一下吧。socket
效果我就不貼了,確定是沒有問題的。今天的就到這裏了。ide