PHP PSR Rate Limiter Middleware

PSR Rate Limiter Middleware

Build Status
Scrutinizer Code Quality
Code Coverage
Latest Stable Version
Total Downloads
LICENSE

It was built on top of Token Bucket.

Installation

composer require razonyang/psr-rate-limiter

Usage

Let's take 5000 requests every hours as example:

// creates a token bucket manager, redis or memcached(built-in)
$capacity = 5000; // each bucket capacity, in other words, maximum number of tokens.
$rate = 0.72; // 3600/5200, how offen the token will be added to bucket
$logger = new \Psr\Log\NullLogger(); // PSR logger
$ttl = 3600; // time to live.
$prefix = 'rateLimiter:'; // prefix.
$manager = new \RazonYang\TokenBucket\Manager\RedisManager($capacity, $rate, $logger, $redis, $ttl, $prefix);

// PSR HTTP response factory
$responseFactory = new \Nyholm\Psr7\Factory\Psr17Factory();

// bucket name callback, let's we treat ip:path as bucket name here
$nameCallback = function (\Psr\Http\Message\ServerRequestInterface $request): string {
    $parameters = $request->getServerParams();
    $path = '';
    $ipKeys = ['HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'REMOTE_ADDR'];
    foreach ($ipKeys as $key) {
        if (!empty($parameters[$key])) {
            return $parameters[$key] . ':' . $request->getUri()->getPath();
        }
    }

    // rate limiting will be skipped when an empty bucket name returned
    return '';
};

$rateLimiter = new \RazonYang\Psr\RateLimiter\Middleware($manager, $responseFactory, $nameCallback);

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据