Skip to content

Commit 452a62c

Browse files
committed
ApiBoot RateLimiter redis方式Lua脚本
1 parent 3dd2cf4 commit 452a62c

File tree

1 file changed

+50
-0
lines changed
  • api-boot-project/api-boot-plugins/api-boot-plugin-rate-limiter/src/main/resources/META-INF/scripts

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
local tokens_key = KEYS[1]
2+
local timestamp_key = KEYS[2]
3+
--redis.log(redis.LOG_WARNING, "tokens_key " .. tokens_key)
4+
5+
local rate = tonumber(ARGV[1])
6+
local capacity = tonumber(ARGV[2])
7+
local now = tonumber(ARGV[3])
8+
local requested = tonumber(ARGV[4])
9+
10+
local fill_time = capacity/rate
11+
local ttl = math.floor(fill_time*2)
12+
13+
--redis.log(redis.LOG_WARNING, "rate " .. ARGV[1])
14+
--redis.log(redis.LOG_WARNING, "capacity " .. ARGV[2])
15+
--redis.log(redis.LOG_WARNING, "now " .. ARGV[3])
16+
--redis.log(redis.LOG_WARNING, "requested " .. ARGV[4])
17+
--redis.log(redis.LOG_WARNING, "filltime " .. fill_time)
18+
--redis.log(redis.LOG_WARNING, "ttl " .. ttl)
19+
20+
local last_tokens = tonumber(redis.call("get", tokens_key))
21+
if last_tokens == nil then
22+
last_tokens = capacity
23+
end
24+
--redis.log(redis.LOG_WARNING, "last_tokens " .. last_tokens)
25+
26+
local last_refreshed = tonumber(redis.call("get", timestamp_key))
27+
if last_refreshed == nil then
28+
last_refreshed = 0
29+
end
30+
--redis.log(redis.LOG_WARNING, "last_refreshed " .. last_refreshed)
31+
32+
local delta = math.max(0, now-last_refreshed)
33+
local filled_tokens = math.min(capacity, last_tokens+(delta*rate))
34+
local allowed = filled_tokens >= requested
35+
local new_tokens = filled_tokens
36+
local allowed_num = 0
37+
if allowed then
38+
new_tokens = filled_tokens - requested
39+
allowed_num = 1
40+
end
41+
42+
--redis.log(redis.LOG_WARNING, "delta " .. delta)
43+
--redis.log(redis.LOG_WARNING, "filled_tokens " .. filled_tokens)
44+
--redis.log(redis.LOG_WARNING, "allowed_num " .. allowed_num)
45+
--redis.log(redis.LOG_WARNING, "new_tokens " .. new_tokens)
46+
47+
redis.call("setex", tokens_key, ttl, new_tokens)
48+
redis.call("setex", timestamp_key, ttl, now)
49+
50+
return { allowed_num, new_tokens }

0 commit comments

Comments
 (0)