redis限流(令牌桶)

核心流程图:

核心lua脚本实现:

local key=KEYS[1]
local num=ARGV[1]
local time=ARGV[2]

result=redis.call("hmget",key,"cur_num","max_num","per_num","last_time")

local cur_num=result[0]
local max_num=result[1]
local per_num=result[2]
local last_time=result[3]

local interval=(tonumber(time)-tonumber(last_time))

cur_num=math.min(max_num,(interval/1000)*per_num)

redis.call("hset",key,"cur_num",cur_num)

result=1
if cur_num>num
    result=1
    redis.call("hset",key,"cur_num",cur_num-num)
    redis.call("hset",key,"last_time",time)
else
    result=0

return result

results matching ""

    No results matching ""