redis 限制接口访问频率

代码:

 1 <?php
 2 
 3 /**
 4  *
 5  */
 6 class myRedis {
 7     private static $redis = null;
 8 
 9     /**
10      * @return null|Redis
11      */
12     public static function instance() {
13         if(self::$redis === null) {
14             $redis = new Redis();
15             $redis->connect('127.0.0.1', 6379);
16             self::$redis = $redis;
17         }
18         return self::$redis;
19     }
20 
21     /**
22      * @param $api
23      * @param string $default
24      * @return string
25      */
26     private static function getApiLimit($api, $default = '3000') {
27         $info = [
28             'user.info' => '500',
29             'user.login' => '1000'
30         ];
31         return isset($info[$api]) ? $info[$api] : $default;
32     }
33 
34     /**
35      * @return bool
36      */
37     public static function check() {
38 
39         $redis = self::instance();
40         $api = "md5_check";
41         $time = self::getApiLimit($api);
42         $key = "api_limit_" . $api;
43 
44         $num = $redis->incr($key);
45 
46         if($num == 1) {
47             $redis->pExpire($key, $time);
48         } else {
49             // echo "false";
50             return false;
51         }
52         // echo "true";
53         return true;
54     }
55 }
View Code

只要在需要限制访问频率的接口处加上 myRedis::check() 即可限制该接口访问平率为 2s 一次

不难发现此代码的逻辑非常简单:

设置 key 的有效时间为 2s,当 key 过期后执行 $redis->incr($key); 的结果为 1,所以,每次 $redis->incr($key); 结果为 1,则说明距离上一次访问达到了 2s,重新设置 key 的有效时间并返回 true 即可,其余情况则返回 false。

原文地址:https://www.cnblogs.com/geloutingyu/p/9513985.html