千万次访问调用
redis做限流-令牌桶的算法
限流模式
拒绝式 兜底数据
排队式 显示当前有多少人
拒绝式
基准测试 来预估机器的瓶颈
客户端->请求->令牌桶 容量:300个(并发只能请求300个)->获取令牌->未获取->拒绝请求
客户端->请求->令牌桶->获取令牌->执行请求的业务->服务器->投递令牌的操作
令牌桶
1.抵御瞬时流量,解决突发的请求
2.改变投递令牌的速率
TrafficShaper.class.php
class TrafficShaper {
public function __construct($config,$queue,$max){
$this->_config = $config;
$this->_queue = $queue;
$this->_max = $max;
$this->_redis = $this->connect();
}
public function add($num=0){
//什么为桶? 投资的方案? 容量是定值
$curnum = intval($this->_redis->lLen($this->_queue));
//协程
$maxnum = intval($this->_max);
$num = $maxnum>=$curnum+$num ? $num :$maxnum-$curnum;
if($num >0){
$token = array_fill(0,$num,1);
foreach($token as $item){
$this->_redis->lPush($this->_queue,$item);
}
return $num;
}
return 0;
}
public function get(){
return $this->_redis->rPop($this->_queue)?true:false;
}
public function reset(){
$this->_redis->delete($this->_queue);
return $this->add($this->_max);
}
}
demo.php
$config = [
'host'=>'127.0.0.1',
'port'=>'6309',
'index' =>0,
'auth'=>'',
'timeout'=>1,
'reserved'=>null,
'retry_interval'=>100
];
$queue = 'mycontainer';
$max = 10;
$oTrafficShaper = new TrafficShaper($config,$queue,$max);
swoole_timer_tick(600,function() use($oTrafficShaper){
$status = $oTrafficShaper->get();
});//毫秒定时器
add.php
$config = [
'host'=>'127.0.0.1',
'port'=>'6309',
'index' =>0,
'auth'=>'',
'timeout'=>1,
'reserved'=>null,
'retry_interval'=>100
];
$queue = 'mycontainer';
$max = 10;
$oTrafficShaper = new TrafficShaper($config,$queue,$max);
swoole_timer_tick(1000,function() use($oTrafficShaper){
$status = $oTrafficShaper->add();
});//毫秒定时器
$config = [
'host'=>'127.0.0.1',
'port'=>'6309',
'index' =>0,
'auth'=>'',
'timeout'=>1,
'reserved'=>null,
'retry_interval'=>100
];
$queue = 'mycontainer';
$max = 10;
$oTrafficShaper = new TrafficShaper($config,$queue,$max);