1.计数器限流 (lua脚本版)
<?php
$redis = getRedis();
// KEYS[1] redis的key, ARGV[1] 时间范围, ARGV[2] 限制次数,
$lua = <<<SCRIPT
-- KEYS[1]为空不通过
if (not KEYS[1])
then
return false
end
-- KEYS[1] 自增1
local incr = redis.call('INCR', KEYS[1])
-- redis异常时直接通过
if (incr == false)
then
return true
end
if (incr > tonumber(ARGV[2]))
then
-- 如果大于最大限制次数,判断KEYS[1]的生命周期是否正常
local ttl = redis.call('TTL', KEYS[1])
if (ttl == -1)
then
-- 如果还未设置,则给KEYS[1]设置生命周期为ARGV[1]
redis.