新增redis固定窗口限流

This commit is contained in:
JaguarJack 2020-06-30 18:06:01 +08:00
parent bd840134ad
commit 1a20159776
2 changed files with 109 additions and 14 deletions

View File

@ -8,3 +8,79 @@
// +---------------------------------------------------------------------- // +----------------------------------------------------------------------
// | Author: JaguarJack [ njphper@gmail.com ] // | Author: JaguarJack [ njphper@gmail.com ]
// +---------------------------------------------------------------------- // +----------------------------------------------------------------------
namespace catcher\library\rate;
use catcher\exceptions\FailedException;
/**
* 固定窗口限流
*
* Class GrantLimit
* @package catcher\library\rate
*/
class GrantLimit
{
use Redis;
protected $ttl = 60;
protected $limit = 1000;
protected $key;
public function __construct($key)
{
$this->key = $key;
$this->init();
}
/**
* 是否到达限流
*
* @time 2020年06月30日
* @return void
*/
public function overflow()
{
if ($this->getCurrentVisitTimes() > $this->limit) {
throw new FailedException('访问限制');
}
$this->inc();
}
/**
* 增加接口次数
*
* @time 2020年06月30日
* @return void
*/
public function inc()
{
$this->getRedis()->incr($this->key);
}
/**
* 初始化
*
* @time 2020年06月30日
* @return void
*/
protected function init()
{
if (!$this->getRedis()->exists($this->key)) {
$this->getRedis()->setex($this->key, $this->ttl, 0);
}
}
/**
* 获取当前访问次数
*
* @time 2020年06月30日
* @return mixed
*/
protected function getCurrentVisitTimes()
{
return $this->getRedis()->get($this->key);
}
}

View File

@ -8,29 +8,48 @@
// +---------------------------------------------------------------------- // +----------------------------------------------------------------------
// | Author: JaguarJack [ njphper@gmail.com ] // | Author: JaguarJack [ njphper@gmail.com ]
// +---------------------------------------------------------------------- // +----------------------------------------------------------------------
namespace catcher\library; namespace catcher\library\rate;
use think\facade\Cache; use think\facade\Cache;
class Redis trait Redis
{ {
protected $handle = null; protected $redis = null;
protected function getRedis()
public function __construct()
{ {
if (!$this->handle) { if (!$this->redis) {
$this->handle = Cache::store('redis')->handler(); $this->redis = Cache::store('redis')->handler();
} }
return $this->handle; return $this->redis;
} }
/**
* 设置 ttl
public function __call($name, $arguments) *
* @time 2020年06月30日
* @param $ttl
* @return $this
*/
public function ttl($ttl)
{ {
// TODO: Implement __call() method. $this->ttl = $ttl;
return $this->handle->{$name}(...$arguments);
return $this;
}
/**
* 设置限制次数
*
* @time 2020年06月30日
* @param $limit
* @return $this
*/
public function limit($limit)
{
$this->limit = $limit;
return $this;
} }
} }