Created
October 20, 2015 07:41
-
-
Save ftwbzhao/b00bf2288cde4b845e84 to your computer and use it in GitHub Desktop.
Yii API Rate Limit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* API服务层 | |
* | |
* 1. 接口访问频率控制(其实应该注册) | |
* <code> | |
* PowerApiService::rateLimit('api-do-something') && apiDoSomething(); | |
* </code> | |
*/ | |
class PowerApiService | |
{ | |
/** | |
* 接口访问频次-频次 | |
*/ | |
public static $RateLimitCount = 5; | |
/** | |
* 接口访问频次-时间段 | |
*/ | |
public static $RateLimitTime = 300; | |
/** | |
* 接口限速器 | |
* base http://redis.readthedocs.org/en/latest/string/incr.html#id3 | |
*/ | |
public static function rateLimit($apiKey = null) | |
{ | |
if (!$apiKey) return false; | |
//这里的IP地址换成Token就nice了 | |
$apiRunCountKey = Yii::app()->request->userHostAddress . '-' . $apiKey; | |
if (self::redisInstance($apiRunCountKey)->get($apiRunCountKey) === false) { | |
//初始化接口访问频次 | |
self::redisInstance($apiRunCountKey)->setex( | |
$apiRunCountKey, | |
self::$RateLimitTime, | |
self::$RateLimitCount | |
); | |
} | |
$currentApiCount = self::redisInstance($apiRunCountKey)->decr($apiRunCountKey); | |
if ($currentApiCount < 0) { | |
Yii::log($apiRunCountKey, 'info', 'api.rate'); | |
return false; | |
} | |
return true; | |
} | |
public static function redisInstance($key) | |
{ | |
return Yii::app()->redis->getRedis($key); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment