使用 Lua 进行速率限制

我们对我们的 Web 服务实现了基于 Redis 的速率限制,该实现取自这里。我在此复制相关代码。

local limits = cjson.decode(ARGV[1])
local now = tonumber(ARGV[2])
local weight = tonumber(ARGV[3] or '1')
local longest_duration = limits[1][1] or 0
local saved_keys = {}
-- 处理清理和限制检查
for i, limit in ipairs(limits) do

local duration = limit[1]
longest_duration = math.max(longest_duration, duration)
local precision = limit[3] or duration
precision = math.min(precision, duration)
local blocks = math.ceil(duration / precision)
local saved = {}
table.insert(saved_keys, saved)
saved.block_id = math.floor(now / precision)
saved.trim_before = saved.block_id - blocks + 1
saved.count_key = duration .. ':' .. precision .. ':'
saved.ts_key = saved.count_key .. 'o'
for j, key in ipairs(KEYS) do

    local old_ts = redis.call('HGET', key, saved.ts_key)
    old_ts = old_ts and tonumber(old_ts) or saved.trim_before
    if old_ts > now then
        -- 不要写到过去
        return 1
    end

    -- 发现需要清理什么
    local decr = 0
    local dele = {}
    local trim = math.min(saved.trim_before, old_ts + blocks)
    for old_block = old_ts, trim - 1 do
        local bkey = saved.count_key .. old_block
        local bcount = redis.call('HGET', key, bkey)
        if bcount then
            decr = decr + tonumber(bcount)
            table.insert(dele, bkey)
        end
    end

    -- 处理清理
    local cur
    if #dele > 0 then
        redis.call('HDEL', key, unpack(dele))
        cur = redis.call('HINCRBY', key, saved.count_key, -decr)
    else
        cur = redis.call('HGET', key, saved.count_key)
    end

    -- 检查我们的限制
    if tonumber(cur or '0') + weight > limit[2] then
        return 1
    end
  end
end

我正在努力弄清楚 -- 不要写到过去 注释的含义 我不明白哪里可能出现 old_ts 大于 now 的情况 我已经在 Lua 代码中添加了很多日志,但未能获得任何成功。

如果有人有见解,那将会很有帮助。

点赞
用户2830850
用户2830850

如果你查看文章中提供的 gist:

https://gist.github.com/josiahcarlson/80584b49da41549a7d5c

有一个评论询问:

在 over_limit_sliding_window_lua_ 函数中,应该

if old_ts > now then

在这里改为

if old_ts > saved.block_id then

我同意这个修改,old_ts 应该拥有 bucket,当 bucket 跳到下一个槽时,old_ts 就会大于 block_id

2019-07-14 08:08:45