日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > HTML >内容正文

HTML

openresty 前端开发入门四之Redis篇

發布時間:2024/4/17 HTML 57 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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篇的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。