php知识点收藏的php代码

API访问频率限制

2017-05-15  本文已影响77人  零一间
<?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}";
}

上一篇 下一篇

猜你喜欢

热点阅读