PHP Redis 限制API和各种接口 请求频率
来保证接口的安全
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<?php require('predis/src/Autoloader.php'); $redis = new Predis\Client(array( 'scheme' => 'tcp', 'host' => '127.0.0.1', 'port' => '6379' )); $redis->auth('123456'); //这个key记录该用户1的访问次数 $key = 'user:1:api_count'; //限制次数为10 $limit = 10; $check = $redis->exists($key); if($check){ $redis->incr($key); $count = $redis->get($key); if($count > 10){ exit('your have too many request'); } }else{ $redis->incr($key); //限制时间为60秒 $redis->expire($key,60); } $count = $redis->get($key); echo 'You have '.$count.' request'; //API业务逻辑 echo '<br/>'; echo 'Hello,World!This is the api content.'; ?> |