问题描述
当系统面对高并发情况时,某些接口达到处理请求瓶颈从来出现拒绝访问,并引发连锁反应导致整个系统崩溃。面对这种特殊情况如何解决?
我们生活中也有类似情景,比如老式电闸都安装了保险丝,一旦有人使用超大功率的设备,保险丝就会烧断以保护各个电器不被强电流给烧坏。同理我们的接口也需要安装上“保险丝”,以防止非预期的请求对系统压力过大而引起的系统瘫痪,当流量过大时,可以采取拒绝或者引流等机制。
方案方案
在开发高并发系统时,有三把利器用来保护系统:缓存、降级和限流。
这里介绍限流。
限流算法
常用的限流算法有两种:漏桶算法和令牌桶算法。
漏桶算法
漏桶算法思路很简单,水(请求)先进入到漏桶里,漏桶以一定的速度出水,当水流入速度过大会直接溢出(等待、丢弃),可以看出漏桶算法能强行限制数据的传输速率。漏桶的剩余空间就代表着当前行为可以持续进行的数量,漏嘴的流水速率代表着系统允许该行为的最大频率。如下图:
PHP 实现
<?php
/**
* 漏捅算法
* Class LeakyBucket
*/
class LeakyBucket
{
private $timeStamp; //当前时间戳
private $capacity = 10; // 桶的容量
private $rate = 2; // 水漏出的速度
private $water; // 当前水量(当前累积请求数)
public function __construct()
{
$this->timeStamp = time();
}
/**
* 桶是否满了
* @return bool
*/
public function grant(){
$now = time();
$this->water = max(0,$this->water - ($now - $this->timeStamp) * $this->rate);// 先执行漏水,计算剩余水量
$this->timeStamp = $now;
if(($this->water + 1) < $this->capacity){
// 尝试加水,并且水还未满
$this->water += 1;
return true;
}else{
// 水满,拒绝加水
return false;
}
}
}
$leakyBucket = new LeakyBucket();
for($i = 0; $i < 20; $i ++) {
$res = $leakyBucket->grant();
var_dump($res);echo "<br>";
//每5秒停1秒,模拟单位时间的请求数
if($i % 5 == 0){
sleep(1);
}
}
//bool(true)
//bool(true)
//bool(true)
//bool(true)
//bool(true)
//bool(true)
//bool(true)
//bool(true)
//bool(true)
//bool(true)
//bool(true)
//bool(true)
//bool(true)
//bool(true)
//bool(false)
//bool(false)
//bool(true)
//bool(true)
//bool(false)
//bool(false)
其他实现
在Redis中,Redis 4.0 版本提供了一个限流 Redis 模块,叫 redis-cell。该模块也使用了漏斗算法,并提供了原子的限流指令。
应用
限制接口、会员、IP单位时间内的访问。
令牌桶算法
对于很多应用场景来说,除了要求能够限制数据的平均传输速率外,还要求允许某种程度的突发传输。这时候漏桶算法可能就不合适了,令牌桶算法更为适合。如下图所示,令牌桶算法的原理是系统会以一个恒定的速度往桶里放入令牌,而如果请求需要被处理,则需要先从桶里获取一个令牌,当桶里没有令牌可取时,则拒绝服务。
PHP + Redis 实现
此算法是对接口访问次数的限制,还有一种是对传输字节数的限制,实现都大同小异,把接口访问次数改成传输的字节大小即可。
<?php
/**
* PHP基于Redis实现令牌桶算法
* Class TokenBucket
*/
class TokenBucket{
// redis连接配置
private $_config = array(
'host' => 'localhost',
'port' => 6379,
'index' => 0,
'auth' => '',
'timeout' => 1,
'reserved' => NULL,
'retry_interval' => 100,
);
private $_redis; // redis对象
private $_queue; // 令牌桶
private $_max; // 最大令牌数
/**
* 初始化
* @param Array $config redis连接设定
* @param string $queue 令牌桶队列
* @param int $max 令牌桶最大令牌数
* @throws Exception
*/
public function __construct($queue, $max, array $config = []){
//传进去的配置优先
if($config){
$this->_config = array_merge($this->_config,$config);
}
$this->_queue = $queue;
$this->_max = $max;
$this->_redis = $this->connect();
}
/**
* 加入令牌
* @param Int $num 加入的令牌数量
* @return Int 加入的数量
*/
public function add($num = 0){
// 当前剩余令牌数
$curnum = intval($this->_redis->lSize($this->_queue));
// 最大令牌数
$maxnum = intval($this->_max);
// 计算最大可加入的令牌数量,不能超过最大令牌数
$num = $maxnum >= $curnum + $num ? $num : $maxnum - $curnum;
// 加入令牌
if($num > 0){
$token = array_fill(0, $num, 1);
$this->_redis->lPush($this->_queue, ...$token);
return $num;
}
return 0;
}
/**
* 获取令牌
* @return Boolean
*/
public function get(){
return $this->_redis->rPop($this->_queue)? true : false;
}
/**
* 重设令牌桶,填满令牌
*/
public function reset(){
$this->_redis->delete($this->_queue);
$this->add($this->_max);
}
/**
* 创建redis连接
* @return Link
* @throws Exception
*/
private function connect(){
try{
$redis = new Redis();
$redis->connect($this->_config['host'],$this->_config['port'],$this->_config['timeout'],$this->_config['reserved'],$this->_config['retry_interval']);
if(empty($this->_config['auth'])){
$redis->auth($this->_config['auth']);
}
$redis->select($this->_config['index']);
}catch(RedisException $e){
throw new Exception($e->getMessage());
return false;
}
return $redis;
}
}
/**
* 测试
* Class TestTokenBucket
*/
class ApiTest
{
/**
* 接口限流
* @param array $config 配置
* @param string $apiName 请求的接口
* @return bool
*/
public function ApiCurrentLimiting(array $config = [],$apiName = '')
{
// 该接口无需限流
if(!array_key_exists($apiName,$config)){
return true;
}
// 创建TokenBucket对象
$tokenBucket = new TokenBucket($config[$apiName]['queue'], $config[$apiName]['max']);
// 获取令牌
$res = $tokenBucket->get();
return $res;
}
}
/**
* 接口需要限流配置
*/
$apiConfig = [
//配置限流接口
'api/test' => [
'queue' => 'testTokenBucket', //令牌桶名称
'max' => '10', //令牌桶大小
],
//其他接口
'api/test01' => [],
'api/test002' => [],
//...
];
$test = new ApiTest();
$api = 'api/test';
// 获取令牌桶实例
$tokenBucket = new TokenBucket($apiConfig[$api]['queue'],$apiConfig[$api]['max']);
// 重设令牌桶,填满令牌,后期可用定时器更新令牌
$tokenBucket->reset();
// 增加令牌
//$add_num = $tokenBucket->add(10);
echo "开始令牌是10个,后面5次拿不到令牌,拒绝处理:<br>";
for($i = 0; $i < 15; $i ++){
//请求接口
$res = $test->ApiCurrentLimiting($apiConfig,'api/test');
var_dump($res);echo "<br>";
}
//bool(true)
//bool(true)
//bool(true)
//bool(true)
//bool(true)
//bool(true)
//bool(true)
//bool(true)
//bool(true)
//bool(true)
//bool(false)
//bool(false)
//bool(false)
//bool(false)
//bool(false)
//下一次添加令牌之后才能继续访问接口,达到单位时间内的接口限流效果
....
更新令牌策略
- 定期加入令牌,我们可以使用crontab实现,每分钟调用add方法加入若干令牌。crontab最小单位是1分钟,可以结合shell脚本,细化到秒为单位的更新。这个效率比较低,每个接口都需要开一个定时任务添加令牌。
- 获取令牌前触发更新机制,判断上次更新时间和现在的时间间隔,大于指定更新时间则添加令牌。增加的令牌和现存令牌之和不能大于令牌桶最大令牌上限。
区别
漏桶算法(Leaky Bucket):主要目的是控制数据注入到网络的速率,平滑网络上的突发流量。漏桶算法提供了一种机制,通过它,突发流量可以被整形以便为网络提供一个稳定的流量。
令牌桶算法:用来控制发送到网络上的数据的数目,并允许突发数据的发送。
两者主要区别在于“漏桶算法”能够强行限制数据的传输速率,而“令牌桶算法”在能够限制数据的平均传输速率外,还允许某种程度的突发传输。在“令牌桶算法”中,只要令牌桶中存在令牌,那么就允许突发地传输数据直到达到用户配置的门限,所以它适合于具有突发特性的流量。
比较
- 令牌桶是按照固定速率往桶中添加令牌,请求是否被处理需要看桶中令牌是否足够,当令牌数减为零时则拒绝新的请求;
- 漏桶则是按照常量固定速率流出请求,流入请求速率任意,当流入的请求数累积到漏桶容量时,则新流入的请求被拒绝;
- 令牌桶限制的是平均流入速率(允许突发请求,只要有令牌就可以处理,支持一次拿3个令牌,4个令牌),并允许一定程度突发流量;
- 漏桶限制的是常量流出速率(即流出速率是一个固定常量值,比如都是1的速率流出,而不能一次是1,下次又是2),从而平滑突发流入速率;
- 令牌桶允许一定程度的突发,而漏桶主要目的是平滑流入速率;
- 两个算法实现可以一样,但是方向是相反的,对于相同的参数得到的限流效果是一样的。
参考资料:
https://blog.youkuaiyun.com/fdipzone/article/details/79352685
https://www.jianshu.com/p/9f76dd2757c7
https://segmentfault.com/a/1190000019556686?utm_source=tag-newest
https://www.ucloud.cn/yun/22455.html