










Redis guarantees the script's atomic execution. While executing the script, all server activities are blocked during its entire runtime. These semantics mean that all of the script's effects either have yet to happen or had already happened.
# 原子占用:INCR;无 TTL 则 EXPIRE;超限 DECR 回滚并返回 -1
_ACQUIRE_LUA = """
local n = redis.call('INCR', KEYS[1])
local ttl = redis.call('PTTL', KEYS[1])
if ttl < 0 then
redis.call('EXPIRE', KEYS[1], tonumber(ARGV[1]))
end
if n > tonumber(ARGV[2]) then
redis.call('DECR', KEYS[1])
return -1
end
return n
"""
"""
尝试占用一次配额。Returns:
>0 当前窗口内占用后的计数;-1 表示已满需等待下一窗口。
"""
result = redis_client.eval(
_ACQUIRE_LUA,
1,
rate_key,
window_seconds + 1,
limit,
)
return int(result)
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。