针对 PHP 的简单速率限制/节流

0.9.4 2022-11-25 16:30 UTC

This package is auto-updated.

Last update: 2024-08-25 20:19:22 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 缓存
  • 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。