php 接口使用场景,接口限流的应用场景

千万次访问调用

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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值