redis.lua 990 B

123456789101112131415161718192021222324252627282930313233343536
  1. --获取上次时间、剩余token
  2. local ratelimit_info = redis.pcall('HMGET', KEYS[1], 'last_time', 'current_token')
  3. local last_time = ratelimit_info[1]
  4. local current_token = tonumber(ratelimit_info[2])
  5. local max_token = tonumber(ARGV[1])
  6. local token_rate = tonumber(ARGV[2])
  7. local current_time = tonumber(ARGV[3])
  8. if current_token == nil then
  9. current_token = max_token
  10. last_time = current_time
  11. else
  12. local past_time = current_time - last_time
  13. --超过一秒,则添加令牌
  14. if past_time > 1000 then
  15. current_token = current_token + token_rate
  16. last_time = current_time
  17. end
  18. --防止令牌超限
  19. if current_token > max_token then
  20. current_token = max_token
  21. last_time = current_time
  22. end
  23. end
  24. local result = 0
  25. if (current_token > 0) then
  26. result = 1
  27. current_token = current_token - 1
  28. last_time = current_time
  29. end
  30. redis.call('HMSET', KEYS[1], 'last_time', last_time, 'current_token', current_token)
  31. return result