openresty 前端开发入门四之Redis篇
生活随笔
收集整理的這篇文章主要介紹了
openresty 前端开发入门四之Redis篇
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
這章主要演示怎么通過lua連接redis,并根據用戶輸入的key從redis獲取value,并返回給用戶
操作redis主要用到了lua-resty-redis庫,代碼可以在github上找得到
而且上面也有實例代碼
由于官網給出的例子比較基本,代碼也比較多,所以我這里主要介紹一些怎么封裝一下,簡化我們調用的代碼
lua/redis.lua
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 secondlocal res = red:connect(config['host'], config['port'])if not res thenreturn nilendif config['pass'] ~= nil thenres = red:auth(config['pass'])if not res thenreturn nilendendred.close = closereturn red endfunction close(self)local sock = self.sockif not sock thenreturn nil, "not initialized"endif self.subscribed thenreturn 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 == "" thenkey = "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?key=hello
即可獲取redis中的key為hello的值,如果沒有key參數,則默認獲取foo的值
ok,到這里我們已經可以獲取用戶輸入的值,并且從redis中獲取數據,然后返回json數據了,已經可以開發一些簡單的接口了
示例代碼 參見demo4部分
轉載于:https://my.oschina.net/362228416/blog/816438
總結
以上是生活随笔為你收集整理的openresty 前端开发入门四之Redis篇的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【powerdesigner】将pdm或
- 下一篇: NeHe OpenGL教程 第二十一课: