我是靠谱客的博主 有魅力老师,这篇文章主要介绍ngx_lua连接redis,现在分享给大家,希望可以做个参考。

复制代码
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
local redis = require("redis") --创建实例 local red = redis:new() --设置超时(毫秒) red:set_timeout(1000) --建立连接 local ip = "127.0.0.1" ngx.say("connect to redis error : ", err) return close_redis(red) end --调用API进行处理 ok, err = red:set("msg", "hello world") if not ok then ngx.say("ok") --调用API获取数据 local resp, err = red:get("msg") if not resp then ngx.say("get msg error : ", err) return close_redis(red) if resp == ngx.null then resp = '' --比如默认值 end ngx.say("msg : ", resp) local redis = require("redis") ngx.say("hello") --创建实例 local red = redis:new() --设置超时(毫秒) red:set_timeout(1000) --建立连接 local ip = "127.0.0.1" local port = 6379 local ok, err = red:connect(ip, port) if not ok then ngx.say("connect to redis error : ", err) return close_redis(red) end --调用API进行处理 ok, err = red:set("msg", "hello world") if not ok then ngx.say("set msg error : ", err) return close_redis(red) end ngx.say("ok") --调用API获取数据 local resp, err = red:get("msg") if not resp then ngx.say("get msg error : ", err) return close_redis(red) end --得到的数据为空处理 if resp == ngx.null then resp = '' --比如默认值 end ngx.say("msg : ", resp) local function close_redis(red) if not red then return end --释放连接(连接池实现) local pool_max_idle_time = 10000 --毫秒 local pool_size = 100 --连接池大小 local ok, err = red:set_keepalive(pool_max_idle_time, pool_size) if not ok then ngx.say("set keepalive error : ", err) end end close_redis(red) local cjson = require "cjson" local redis = require "redis" local red1 = redis:new() local red2 = redis:new() red1:set_timeout(1000) -- 1 sec red2:set_timeout(1000) -- 1 sec https://github.com/openresty/lua-resty-redis local ok, err = red1:connect("127.0.0.1", 6379) if not ok then ngx.say("1: failed to connect: ", err) return end ok, err = red2:connect("127.0.0.1", 6379) if not ok then ngx.say("2: failed to connect: ", err) return end local res, err = red1:subscribe("dog") if not res then ngx.say("1: failed to subscribe: ", err) return end ngx.say("1: subscribe: ", cjson.encode(res)) res, err = red2:publish("dog", "Hello") if not res then ngx.say("2: failed to publish: ", err) return end ngx.say("2: publish: ", cjson.encode(res)) res, err = red:read_reply() if not res then ngx.say("1: failed to read reply: ", err) return end ngx.say("1: receive: ", cjson.encode(res)) close_redis(red1) close_redis(red2) 需求, 利用lua监控redis的订阅发布,

最后

以上就是有魅力老师最近收集整理的关于ngx_lua连接redis的全部内容,更多相关ngx_lua连接redis内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(74)

评论列表共有 0 条评论

立即
投稿
返回
顶部