Skip to content

Instantly share code, notes, and snippets.

@ftwbzhao
Created October 20, 2015 07:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ftwbzhao/b00bf2288cde4b845e84 to your computer and use it in GitHub Desktop.
Save ftwbzhao/b00bf2288cde4b845e84 to your computer and use it in GitHub Desktop.
Yii API Rate Limit
<?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