farit-slv /

guzzle-throttle-middleware

一个在发送请求之前可以延迟请求的 GuzzleHTTP 中间件。

0.5.1 2024-02-04 13:55 UTC

This package is auto-updated.

Last update: 2024-09-04 15:14:58 UTC


README

Latest Stable Version License Build Status Coverage Status Quality Score Total Downloads

Guzzle 速率限制中间件

此中间件为您的 Guzzle 客户端添加速率限制功能。

当某些主机限制了您每秒/每分钟请求的数量时,这可能很有用。

安装

composer require farit-slv/guzzle-throttle-middleware

计数器存储

默认情况下,请求计数器存储在数组中。

但是,您可以使用 PSR6Adapterpsr/cache 实现中存储您的计数器,例如 symfony/cache,并使用共享存储如 Redis、APCu、Memcached 等。

使用方法

为了使此中间件正常工作,您需要注册一些配置。

配置由以下组成

  • 一个请求匹配器(根据请求内容触发或禁用速率限制器)
  • 最大请求数量
  • 在秒内应用最大请求数量的周期。
  • 一个存储密钥。

您可以注册所需的任何数量的配置。第一个请求匹配器获胜。

示例

namespace App\RequestMatcher;

use BenTools\Psr7\RequestMatcherInterface;
use Psr\Http\Message\RequestInterface;

class ExampleOrgRequestMatcher implements RequestMatcherInterface
{
    /**
     * @inheritDoc
     */
    public function matchRequest(RequestInterface $request)
    {
        return false !== strpos($request->getUri()->getHost(), 'example.org');
    }
}
use App\RequestMatcher\ExampleOrgRequestMatcher;
use FaritSlv\GuzzleHttp\Middleware\Storage\Adapter\ArrayAdapter;
use FaritSlv\GuzzleHttp\Middleware\ThrottleConfiguration;
use FaritSlv\GuzzleHttp\Middleware\ThrottleMiddleware;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

require_once __DIR__ . '/vendor/autoload.php';

$stack = HandlerStack::create();
$middleware = new ThrottleMiddleware(new ArrayAdapter());

// Max 1 request per second
$maxRequests = 1;
$durationInSeconds = 1;
$middleware->registerConfiguration(
    new ThrottleConfiguration(new ExampleOrgRequestMatcher(), $maxRequests, $durationInSeconds, 'example')
);

$stack->push($middleware, 'throttle');
$client = new Client([
    'handler' => $stack,
]);

$client->get('http://www.example.org'); // Will be executed immediately
$client->get('http://www.example.org'); // Will be executed in 1 second

测试

./vendor/bin/phpunit

已知问题

由于 PHP 的同步行为,请记住,速率限制意味着调用 sleep()usleep() 函数,这将延迟整个脚本,而不仅仅是当前请求。

这意味着当使用 CurlMultiHandler 时,速率限制也会阻塞 Guzzle 的异步请求。

为了防止这种情况,您可以查看 bentools/guzzle-queue-handler,这是一个将异步请求委托给 PHP 工作者的处理器(Beanstalk、RabbitMQ、Redis 等)。

然后您可以在工作者上启用速率限制。

另请参阅