openresty 前端開發入門四之Redis篇

2021-09-20 05:59:10 字數 1732 閱讀 5460

這章主要演示怎麼通過lua連線redis,並根據使用者輸入的key從redis獲取value,並返回給使用者

操作redis主要用到了lua-resty-redis庫,**可以在github上找得到

而且上面也有例項**

由於官網給出的例子比較基本,**也比較多,所以我這裡主要介紹一些怎麼封裝一下,簡化我們呼叫的**

lua/redis.lua

local redis = require "resty.redis"

local config =

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

endif config['pass'] ~= nil then

res = red:auth(config['pass'])

if not res then

return nil

endend

red.close = close

return red

endfunction close(self)

local sock = self.sock

if not sock then

return nil, "not initialized"

endif self.subscribed then

return nil, "subscribed state"

endreturn sock:setkeepalive(10000, 50)

endreturn _m

其實就是簡單把連線,跟關閉做乙個簡單的封裝,隱藏繁瑣的初始化已經連線池細節,只需要呼叫new,就自動就鏈結了redis,close自動使用連線池

lua/hello.lua

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 =

ngx.say(cjson.encode(data))

訪問

即可獲取redis中的key為hello的值,如果沒有key引數,則預設獲取foo的值

ok,到這裡我們已經可以獲取使用者輸入的值,並且從redis中獲取資料,然後返回json資料了,已經可以開發一些簡單的介面了

示例** 參見demo4部分

openresty 前端開發入門二

這一章主要介紹介紹怎麼獲取請求引數,並且處理之後返回資料 我們知道http請求通常分為兩種,分別是get,post,在http協議中,get引數通常會緊跟在uri後面,而post請求引數則包含在請求體中,nginx預設情況下是不會讀取post請求引數的,最好也不要試圖使改變這種行為,因為大多數情況下...

openresty 開發入門

文章目錄 1 openresty 安裝 2 lua 測試程式 3 nginx.conf 檔案配置 4 系統啟動1 openresty 安裝 2 tar xzvf openresty 1.9.15.1.tar.gz 3 進入 openresty 1.9.15.1 4 configure prefix ...

openresty 前端開發入門五之Mysql篇

openresty 前端開發入門五之mysql篇 這章主要演示怎麼通過lua連線mysql,並根據使用者輸入的name從mysql獲取資料,並返回給使用者 操作mysql主要用到了lua resty mysql庫,可以在 github 上找得到 而且上面也有例項 由於官網給出的例子比較基本,也比較多...