openresty && hashids&& redis 生成短鏈接

1. 原理

a. 從redis 獲取需要表示的短鏈接的id( redis incr)

b. hashids 編碼 id

c. openresty ?conteent_by_lua_block 階段顯示數(shù)據(jù)

2. 安裝以來的插件

a. lua hashdis ?使用 ?luarocks 注意需要先安裝lua 開發(fā)包

b. copy hashids lua 包 到 openresty 的lualib ?方便調(diào)用

c. redis 安裝

luarocks install hashids

3. 代碼

nginx 配置格式

location /test {

content_by_lua_block {

-- 此處為偽代碼,需要自己處理,代碼見下面的

ngx.say(hashid)

}

}

a. redis id 生成

local hashids = require("hashids");

local redis = require "resty.redis"

local red = redis:new()

local ids= 1;

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

end

ids, err = red:incrby("ids", 1)

if not ok then

ngx.say("failed to set ids: ", err)

return

end

-- ngx.say("set result: ", ok)

local ok, err = red:set_keepalive(10000, 100)

if not ok then

ngx.say("failed to set keepalive: ", err)

return

end

b. hashids 生成短鏈接

local h = hashids.new("dalong")

hash = h:encode(ids)

ngx.say(hash)

c. 訪問

http://ip:port/test產(chǎn)看效果


d. 次代碼可以進(jìn)行decode 獲取id,中的來說還是比較方便的

local hashids = require("hashids");

local h = hashids.new("dalong")

hash = h:decode("y71ZEKxm")

print(hash[1])

4. 擴(kuò)展

實(shí)際系統(tǒng)如果使用還需要考慮redis 的高可用,安全,以及如何進(jìn)行數(shù)據(jù)分析的問題

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容