Redis应用场景限流算法之一,计数器算法代码
Redis  /  管理员 发布于 4年前   1306
众所周知,现在常见的限流算法有三种
1.计数器
2.漏桶
3.令牌桶
这仨种。
本文介绍的就是第一种:计数器限流算法的编写与测试
原理:
确定方法的最大访问量MAX,每次进入方法前计数器+1,将结果和最大并发量MAX比较,如果大于等于MAX,则直接返回;
如果小于MAX,则继续执行。
测试环境:
hyperf2.1框架
redis 有序集合
计数器算法编写,这里我专门创建一下控制器用来运行:
<?php
declare(strict_types=1);
namespace App\Controller;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\View\RenderInterface;
use Hyperf\Utils\ApplicationContext;
use Hyperf\HttpServer\Annotation\AutoController;
/**
* @AutoController()
*/
class TestController
{
public function index(RenderInterface $render,ResponseInterface $response,RequestInterface $request)
{
return $response->json('测试专用控制器');
}
public function test(RenderInterface $render,ResponseInterface $response)
{
//return $response->json('test', ['name' => 'ttttttttHyperf']);
for ($i=0; $i<10; $i++){
//执行可以发现只有前5次是通过的
var_dump($this->Calculator("1", "reply", 60, 5));
//这里做个秒限制 太快了会有漏网之鱼
sleep (1);
}
return $response->json('执行完');
}
/**计数器限流算法
* @param $uid 客户端id
* @param $action 动作
* @param $second 时间秒
* @param $num 数量
*/
public function Calculator($uid,$action,$second,$num)
{
$redis = ApplicationContext::getContainer()->get(\Hyperf\Redis\Redis::class);
$key = sprintf('hist:%s:%s', $uid, $action);
//当前的毫秒时间戳
list($msec, $sec) = explode(' ', microtime());
$now = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
//使用管道提升性能
$pipe = $redis->multi(\Redis::PIPELINE);
//value 和 score 都使用毫秒时间戳
$pipe->zAdd($key, $now, $now);
//移除时间窗口之前的行为记录,剩下的都是时间窗口内的
$pipe->zRemRangeByScore($key, '0',(string)($now - $second * 1000));
//获取窗口内的行为数量
$pipe->zCard($key);
//多加一秒过期时间
$pipe->expire($key, $second + 1);
$replies = $pipe->exec();
//打印出来看看 等下截图用
print_r($replies);
return $replies[2] <= $num;
}
}
运行起来测试一下
上面变量$replies打印出来的值 , 观看起来更直观
看每个数组后面的布尔值,前面5个是true 后面的为false
这结果就是我们计数器限流算法运行的结果
Array
(
[0] => 1
[1] => 0
[2] => 1
[3] => 1
)
bool(true)
Array
(
[0] => 1
[1] => 0
[2] => 2
[3] => 1
)
bool(true)
Array
(
[0] => 1
[1] => 0
[2] => 3
[3] => 1
)
bool(true)
Array
(
[0] => 1
[1] => 0
[2] => 4
[3] => 1
)
bool(true)
Array
(
[0] => 1
[1] => 0
[2] => 5
[3] => 1
)
bool(true)
Array
(
[0] => 1
[1] => 0
[2] => 6
[3] => 1
)
bool(false)
Array
(
[0] => 1
[1] => 0
[2] => 7
[3] => 1
)
bool(false)
Array
(
[0] => 1
[1] => 0
[2] => 8
[3] => 1
)
bool(false)
Array
(
[0] => 1
[1] => 0
[2] => 9
[3] => 1
)
bool(false)
Array
(
[0] => 1
[1] => 0
[2] => 10
[3] => 1
)
bool(false)
总结
该算法需要限制一下运行速度,太快会有漏网之鱼,所以上面我用了sleep(1) 确保万无一失
你要根据需求选择该限流计数器算法
后面我会编写后面两种限流算法: 2.漏桶 3.令牌桶 并进行场景测试
完
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号