Skip to content

Commit ef2b739

Browse files
authored
optimize: resty.limit.conn call dict:incr with init_ttl argument. (#67)
1 parent 1a5ebce commit ef2b739

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

lib/resty/limit/count.lua

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,15 @@ local mt = {
1515
__index = _M
1616
}
1717

18+
local incr_support_init_ttl
19+
local ngx_config = ngx.config
20+
local ngx_lua_v = ngx.config.ngx_lua_version
21+
if not ngx_config or not ngx_lua_v or (ngx_lua_v < 10012) then
22+
incr_support_init_ttl = false
23+
else
24+
incr_support_init_ttl = true
25+
end
26+
1827

1928
-- the "limit" argument controls number of request allowed in a time window.
2029
-- time "window" argument controls the time window in seconds.
@@ -35,8 +44,33 @@ function _M.new(dict_name, limit, window)
3544
return setmetatable(self, mt)
3645
end
3746

47+
-- incoming function using incr with init_ttl
48+
-- need OpenResty version > v0.10.12rc2
49+
local function incoming_new(self, key, commit)
50+
local dict = self.dict
51+
local limit = self.limit
52+
local window = self.window
53+
54+
local remaining, ok, err
55+
56+
if commit then
57+
remaining, err = dict:incr(key, -1, limit, window)
58+
if not remaining then
59+
return nil, err
60+
end
61+
else
62+
remaining = (dict:get(key) or limit) - 1
63+
end
64+
65+
if remaining < 0 then
66+
return nil, "rejected"
67+
end
68+
69+
return 0, remaining
70+
end
3871

39-
function _M.incoming(self, key, commit)
72+
-- incoming function using incr and expire
73+
local function incoming_old(self, key, commit)
4074
local dict = self.dict
4175
local limit = self.limit
4276
local window = self.window
@@ -80,6 +114,7 @@ function _M.incoming(self, key, commit)
80114
return 0, remaining
81115
end
82116

117+
_M.incoming = incr_support_init_ttl and incoming_new or incoming_old
83118

84119
-- uncommit remaining and return remaining value
85120
function _M.uncommit(self, key)

0 commit comments

Comments
 (0)