otzy/intensity-throttle

使用漏桶算法限制任何类型事件的速率

v1.0.0 2016-07-18 23:31 UTC

This package is not auto-updated.

Last update: 2024-09-23 14:23:39 UTC


README

#IntensityThrottle

使用IntensityThrottle包,您可以轻松限制任何类型事件的速率。例如,您可以监控服务器请求的速率或cron作业中的错误速率。

IntensityThrottle实现了漏桶算法,这意味着您不仅可以设置带宽,还可以设置突发性。也就是说,事件速率的短期峰值是可能的。

由于PHP的特性,泄漏并不是定期发生的(不是连续的),而是在处理事件的时候发生。这稍微改变了桶的行为,但最终它们仍然完成了它们的工作。

##使用方法

该包包含InProcessStorage,当您需要限制单个进程中的事件时可以使用它,例如在长时间运行的cron作业中。

use Otzy\Intensity\InProcessStorage;
use Otzy\Intensity\IntensityThrottle;

//Create throttle
$throttle = new IntensityThrottle('test', new InProcessStorage());

//add leaky bucket to the throttle. You can add so many buckets as you wish
$max_drops = 3; //this is a backet volume
$time_span = 1; //how long it takes to get bucket empty

//add a bucket
$throttle->addLimit($max_drops, $time_span)

//simulate events
$start = microtime(true);
for ($i = 0; $i < 100; $i++) {

    //Register event. If buckets get overflowed, the method drip() returns false. If there is still space in them, it returns true
    $drip_result = $throttle->drip();

    if ($drip_result === false) {
        printf("Throttle Test: Drops limit exceeded after %.3f seconds.", (microtime(true) - $start));
        return;
    }

    usleep(250000);
}

如果您想限制跨不同请求和/或服务器的Web请求或其他事件,您应该使用memcached服务器。您可以直接使用Memcached类作为存储。

$memcached = new \Memcached();
$memcached->addServer('localhost', 11211);
$throttle = new IntensityThrottle('test', $memcached);

##桶容量

$throttle->addLimit($max_drops, $time_span)添加容量为$max_drops的桶。

乍一看,$throttle->addLimit(3, 1)$throttle->addLimit(6, 2)是相同的。第二个桶的容量是第一个的两倍,泄漏率也是两倍。所以如果平均事件速率是每秒3个事件,两个桶都不会溢出。

区别在于第二个桶能够支持更高的突发性速率,即事件流中的暂时不均匀性。

上面的例子(桶容量为3)将在2.255秒后停止。如果您将$throttle->addLimit(3, 1)替换为$throttle->addLimit(6, 2),脚本将在5.26秒后停止。