Home > Article > Backend Development > PHP+Redis solves the practical problem of order flow limitation
1. Each issue of this series of articles will solve a practical Redis problem.
2. The questions of each issue will be selected from the comments of each issue.
3. The questions are limited to Redis related. For other questions, if I If you are interested, I don’t rule out starting a new series
4. I often use PHP, so the solution is mainly PHP
5. If there are no suitable questions in the comments, I will make up my own questions
Problem description:
This is the first issue, so I can only come up with my own questions
How to use Redis to limit the flow of orders, For example, N accesses are allowed every M seconds
Solution:
<?php /** * 是否允许放行 * @param string $key redis键前缀 * @param int $timeInterval 时间间隔(秒) * @param int $max 时间间隔内最大放行数 * @return bool 是否放行 * @throws Exception * @example * <pre class="brush:php;toolbar:false"> * //每秒放行一个 * 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; }
Code interpretation:
Modulo the time, Make the key name updated every $timeInterval seconds
incr() method increments the value of the key. If the key does not exist, first create a key with a value of 0 and then increment
According to the principle of auto-increment, the value returned by the Nth auto-increment under the same key name is N
The key name is updated every $timeInterval seconds. Therefore, the key will no longer have value
or more after the $timeInterval of creating the key for 1 second. Everyone is welcome to ask questions, correct errors, supplement, and optimize.
Recommended: "PHP Video Tutorial"
The above is the detailed content of PHP+Redis solves the practical problem of order flow limitation. For more information, please follow other related articles on the PHP Chinese website!