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

1. 原理
    a. 从redis 获取需要表示的短链接的id( redis incr)
    b. hashids 编码 id
    c. openresty  conteent_by_lua_block 阶段显示数据
 
2. 安装以来的插件
 
   a. lua hashdis  使用  luarocks 注意需要先安装lua 开发包
   b. copy hashids lua 包 到 openresty 的lualib  方便调用
   c. redis 安装
 
1
luarocks install hashids
3. 代码
 nginx 配置格式
 
1
2
3
4
5
6
location /test {
content_by_lua_block {
-- 此处为伪代码,需要自己处理,代码见下面的
ngx.say(hashid)
}
}

  

 a. redis id 生成
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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 生成短链接
1
2
3
local h = hashids.new("dalong")
hash = h:encode(ids)
ngx.say(hash)
c. 访问
http://ip:port/test 产看效果
 
 d. 次代码可以进行decode 获取id,中的来说还是比较方便的
1
2
3
4
local hashids = require("hashids");
local h = hashids.new("dalong")
hash = h:decode("y71ZEKxm")
print(hash[1])
 
4. 扩展
  
  1. 实际系统如果使用还需要考虑redis 的高可用,安全,以及如何进行数据分析的问题
 
 

posted on   荣锋亮  阅读(1038)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2015-06-18 浏览器的标准模式和怪异模式

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示