redisutil.lua
1.9 KB
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
#! /usr/bin/env lua
--[[
redis操作库
--]]
local resty_redis = require("resty.redis")
Redis ={}
function Redis:new(datasource)
local o={}
o.datasource = datasource or {
host = "127.0.0.1",
port = "6379",
auth = nil,
timeout = 3000,
max_idle_timeout = 60000,
pool_size = 1000
}
setmetatable(o,self)
self.__index=self
ngx.log(ngx.DEBUG, "[Redis:init] datasource ")
return o
end
function Redis:getConnect()
local connect, err = resty_redis:new()
if not connect then
ngx.log(ngx.ERR, "[Redis:getConnect] failed to create redis : " .. self.datasource.host, err)
return nil
end
connect:set_timeout(self.datasource.timeout)
local ok, err = connect:connect(self.datasource.host, self.datasource.port)
if not ok then
ngx.log(ngx.ERR, "[Redis:getConnect] failed to connect redis : " .. self.datasource.host, err)
return nil
end
if self.datasource.auth then
local res, err = connect:auth(self.datasource.auth)
end
return connect
end
function Redis:cmd(method, ...)
local connect = self:getConnect()
if not connect then
return nil
end
ngx.log(ngx.DEBUG, "[Redis:cmd] connected to redis ok.")
-- exec cmd
local res, err = connect[method](connect, ...)
-- close
self:close(connect)
return res, err
end
function Redis:close(connect)
if not connect then
return
end
if self.datasource.pool_size <= 0 then
connect:close()
return
end
-- put it into the connection pool of size 100,
-- with 10 seconds max idle timeout
local ok, err = connect:set_keepalive(self.datasource.max_idle_timeout, self.datasource.pool_size)
if not ok then
ngx.log(ngx.ERR, "[Redis:close] set keepalive failed : ", err)
else
ngx.log(ngx.DEBUG, "[Redis:close] set keepalive ok.")
end
end
return Redis