avaibook/symfony-rate-limiter

Symfony RateLimiter 组件的 Sf4.4 兼容性补丁,该组件提供了一种令牌桶的实现,用于在您的应用程序中对输入和输出进行速率限制

4.4 2021-10-06 12:43 UTC

This package is not auto-updated.

Last update: 2024-09-20 01:31:51 UTC


README

速率限制组件提供了一种令牌桶实现,用于在您的应用程序中对输入和输出进行速率限制。

这是对 原始包 的分支,使其与 Symfony <= 4.4 兼容。

该组件为实验性实验性功能 不受 Symfony 的 向后兼容承诺 的约束。

入门

$ composer require avaibook/symfony-rate-limiter
use Symfony\Component\RateLimiter\Storage\InMemoryStorage;
use Symfony\Component\RateLimiter\RateLimiterFactory;

$factory = new RateLimiterFactory([
    'id' => 'login',
    'policy' => 'token_bucket',
    'limit' => 10,
    'rate' => ['interval' => '15 minutes'],
], new InMemoryStorage());

$limiter = $factory->create();

// blocks until 1 token is free to use for this process
$limiter->reserve(1)->wait();
// ... execute the code

// only claims 1 token if it's free at this moment (useful if you plan to skip this process)
if ($limiter->consume(1)->isAccepted()) {
   // ... execute the code
}

资源