Implementing Redis-Based Rate Limiting in PHP
This article presents a PHP implementation of Redis-based rate limiting, explaining how to limit the number of requests per time interval by using timestamp-modulo keys, atomic increment operations, and key expiration, along with detailed code and step-by-step commentary.
This article addresses the practical problem of implementing rate limiting for orders using Redis, allowing a configurable number of accesses per defined time interval.
It provides a PHP function isAllow that determines whether a request should be permitted based on a Redis key that incorporates the current timestamp modulo the interval, incrementing the counter atomically and setting an expiration.
<?php
/**
* 是否允许放行
* @param string $key redis键前缀
* @param int $timeInterval 时间间隔(秒)
* @param int $max 时间间隔内最大放行数
* @return bool 是否放行
* @throws Exception
* @example
* //每秒放行一个
* isAllow('my_allow');
*
* //每秒放行3个
* isAllow('my_allow',1,3);
*
* //每3秒放行2个
* isAllow('my_allow',3,2);
*/
function isAllow(string $key, int $timeInterval=1, int $max=1):bool{
if($timeInterval<1){
throw new Exception('时间间隔必须大于0');
}
if($max<1){
throw new Exception('最大放行数必须大于0');
}
$redis = new Redis();
$redis->connect('192.168.31.187');
if(!$redis->isConnected()){
throw new Exception('Redis服务连接失败');
}
//对时间戳取模,使得每$timeInterval秒取得同一个时间戳
$time = time();
$key .= ':' . ($time - ($time % $timeInterval));
//自增并返回自增后的结果
$index = $redis->incr($key);
//如果是第一个访问,设置键的过期时间
if($index === 1){
$redis->expire($key, $timeInterval + 1);
}
return $index < $max + 1;
}
?>The accompanying explanation highlights four key points: the timestamp modulo creates a key that refreshes every interval; incr() atomically increments the counter, creating the key if absent; the returned value indicates the request order; and the key expires shortly after the interval, ensuring it does not persist.
Readers are invited to ask questions, suggest corrections, or propose optimizations.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
