123456789101112131415161718192021222324252627282930313233343536 |
- --获取上次时间、剩余token
- local ratelimit_info = redis.pcall('HMGET', KEYS[1], 'last_time', 'current_token')
- local last_time = ratelimit_info[1]
- local current_token = tonumber(ratelimit_info[2])
- local max_token = tonumber(ARGV[1])
- local token_rate = tonumber(ARGV[2])
- local current_time = tonumber(ARGV[3])
- if current_token == nil then
- current_token = max_token
- last_time = current_time
- else
- local past_time = current_time - last_time
- --超过一秒,则添加令牌
- if past_time > 1000 then
- current_token = current_token + token_rate
- last_time = current_time
- end
- --防止令牌超限
- if current_token > max_token then
- current_token = max_token
- last_time = current_time
- end
- end
- local result = 0
- if (current_token > 0) then
- result = 1
- current_token = current_token - 1
- last_time = current_time
- end
- redis.call('HMSET', KEYS[1], 'last_time', last_time, 'current_token', current_token)
- return result
|