<?php
/**
* API访问频率限制简单处理
*/
require_once 'vendor/autoload.php';
$redis = new Predis\Client ( 'tcp://127.0.0.1:6379' );
// 测试key
$clientKey = "api_count:client_id:" . date ( 'YmdHi' );
// 限制时间为1分钟
$seconds = '60';
// 限制次数为20次
$count = 20;
//不存在key
if (! $redis->get ( $clientKey )) {
$redis->set ( $clientKey, 0 );
$redis->expire ( $clientKey, $seconds );
}
//访问频率监控
$accessCount = $redis->incr ( $clientKey );
if ($accessCount > $count) {
echo "[WARING]:访问超过限制次数";
} else {
$remainingTime = $redis->ttl ( $clientKey );
echo "{$clientKey} 剩余时间:{$remainingTime}s 访问次数为:{$accessCount}";
}
网友评论