leaducate/stiphle-leaducate

php的简单限速/节流

0.9.2 2017-08-16 07:58 UTC

This package is auto-updated.

Last update: 2024-09-29 05:09:27 UTC


README

通过Composer安装

composer require davedevelopment/stiphle

这是什么?

Stiphle 是一个小型库,旨在提供一种简单的方法来限制/节流请求,适用于没有复杂硬件等设备的情况。

它是如何工作的?

您创建一个节流器,并询问它应该等待多长时间。例如,给定 $identifier 是识别您要节流的任何东西的一种方式,并且您希望将其限制为每秒5个请求

<?php

$throttle = new Stiphle\Throttle\LeakyBucket;
$identifier = 'dave';
while(true) {
    // the throttle method returns the amount of milliseconds it slept for
    echo $throttle->throttle($identifier, 5, 1000);
}
# 0 0 0 0 0 200 200....

使用组合值来提供突发等,但请谨慎使用,因为它会干扰您的思路

<?php

$throttle = new Stiphle\Throttle\LeakyBucket;
$identifier = 'dave';
for(;;) {
    /**
     * Allow upto 5 per second, but limit to 20 a minute - I think
     **/
    echo "a:" . $throttle->throttle($identifier, 5, 1000);
    echo " b:" . $throttle->throttle($identifier, 20, 60000);
    echo "\n";
}
#a:0 b:0
#a:0 b:0
#a:0 b:0
#a:0 b:0
#a:0 b:0
#a:199 b:0
#a:200 b:0
#a:199 b:0
#a:200 b:0
#a:200 b:0
#a:199 b:0
#a:200 b:0
#a:199 b:0
#a:200 b:0
#a:200 b:0
#a:199 b:0
#a:200 b:0
#a:200 b:0
#a:199 b:0
#a:200 b:0
#a:199 b:0
#a:200 b:2600
#a:0 b:3000
#a:0 b:2999

节流策略

目前有两种类型的节流器,漏桶 和简单的固定时间窗口。

/**
 * Throttle to 1000 per *rolling* 24 hours, e.g. the counter will not reset at
 * midnight
 */
$throttle = new Stiphle\Throttle\LeakyBucket;
$throttle->throttle('api.request', 1000, 86400000);

/**
 * Throttle to 1000 per calendar day, counter will reset at midnight
 */
$throttle = new Stiphle\Throttle\TimeWindow;
$throttle->throttle('api.request', 1000, 86400000);

注意:当前 TimeWindow 节流器的实现只能在64位架构上工作!

存储

Stiphle 目前提供了5种存储引擎

  • 进程内
  • APC
  • Memcached
  • Doctrine Cache
  • Redis

Stiphle 默认使用进程内存储。可以在对象创建后注入不同的存储引擎。

$throttle = new Stiphle\Throttle\LeakyBucket();
$storage = new \Stiphle\Storage\Memcached(new \Memcached());
$throttle->setStorage($storage);

待办事项

  • 更多测试!
  • 合理的 单元 测试
  • 更多的节流方法
  • 更多的存储适配器,当前的这些有些易变,Mongo、Cassandra、MemcacheDB 等

版权

版权 (c) 2011 Dave Marshall。有关更多详细信息,请参阅 LICENCE。