dnomyar/php-rate-limiter

简单的速率限制器

1.0.2 2022-09-01 17:03 UTC

This package is auto-updated.

Last update: 2024-09-29 05:57:14 UTC


README

这是一个低成本速率限制器。低成本是因为它不需要任何额外的工具即可工作。它使用文件系统作为存储库。它可以用来保护公共表单免受机器人攻击或按用户限制。

当前实现允许原子地更新存储桶。如果另一个请求尝试在同一时间更新相同的存储桶,它将抛出异常。

用法

此库提供了一个需要用标识符初始化的 RateLimiter 类,该标识符对应于需要限制的资源。例如

  • 限制提交到公共页面的次数。在这种情况下,ID可以是 business-description
  • 限制每个用户的调用次数。在这种情况下,ID可以是 business-description-
use Dnomyar\PhpFileSystemRateLimiter\Domain\RateLimiter;
use Dnomyar\PhpFileSystemRateLimiter\Domain\Model\Configuration\BucketSize;
use Dnomyar\PhpFileSystemRateLimiter\Domain\Model\Configuration\BucketTime;
use Dnomyar\PhpFileSystemRateLimiter\Domain\Model\Configuration\Duration;
use Dnomyar\PhpFileSystemRateLimiter\Infrastructure\Repository\LockFileImplementation;
use Dnomyar\PhpFileSystemRateLimiter\Infrastructure\Repository\BucketSerializerImplementation;
use Dnomyar\PhpFileSystemRateLimiter\Infrastructure\Repository\FileSystemFileAdapterImplementation;
use Dnomyar\PhpFileSystemRateLimiter\Infrastructure\Repository\FileSystemBucketRepository;

$rateLimiter = new RateLimiter(
     new BucketTime(Duration::seconds(10)),
     BucketSize::createBucketSize(6),
     new FileSystemBucketRepository(
        new FileSystemFileAdapterImplementation(),
        new BucketSerializerImplementation(),
        new LockFileImplementation()
     )
);

/*
 * return true of false if the call is allowed
 * thows a BucketRepositoryException if another request is trying to use the feature at the same time.
 */
$rateLimiter->allowCall('id-to-change');

限制

如果您打算在项目中使用它,请谨慎行事。此库是为了遵守两个重要的约束条件而构建的:不使用额外的工具和相同的标识符的低级别并行请求。

此外,在负载高峰期间可能会出现问题。建议在使用此库之前进行负载测试。