代碼:

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 }
只要在需要限制訪問頻率的接口處加上 myRedis::check() 即可限制該接口訪問平率為 2s 一次
不難發現此代碼的邏輯非常簡單:
設置 key 的有效時間為 2s,當 key 過期后執行 $redis->incr($key); 的結果為 1,所以,每次 $redis->incr($key); 結果為 1,則說明距離上一次訪問達到了 2s,重新設置 key 的有效時間並返回 true 即可,其余情況則返回 false。