使用redis解决限流

安装redis(跳过)

编写limit.lua

local info = redis.pcall("hmget", KEYS[1], "prev_time", "cur_permits", "max_permits", "rate");
local prev_time = tonumber(info[1]);
local cur_permits = tonumber(info[2]);
local max_permits = tonumber(info[3])
local rate = tonumber(info[4])
local time_table = redis.pcall("time");
local seconds = tonumber(time_table[1]);
local micro_seconds = tonumber(time_table[2]);
local cur_time = math.floor((seconds*1000000 + micro_seconds)/1000);
local elapsed =  math.floor((cur_time - prev_time)/1000);
local new_permits = elapsed*rate;
cur_permits = math.min(cur_permits + new_permits, max_permits);
redis.pcall("hset",KEYS[1],"prev_time",cur_time);
if (cur_permits >= 1) then
    redis.pcall("hset",KEYS[1],"cur_permits",cur_permits-1);
    return 1;
end
redis.pcall("hset",KEYS[1],"cur_permits",cur_permits);
return 0

准备key

hset ratetest prev_time 1562821078 cur_permits 0 max_permits 10 rate 1

测试

redis-cli --eval limit.lua ratetest

这个代码是限制每秒最大10次,然后每秒恢复一次

你可能感兴趣的:(使用redis解决限流)