2021-06-07 526次浏览

First version of yiisoft/rate-limiter package was released.

RateLimiter helps to prevent abuse by limiting the number of requests that could be me made consequentially.

For example, you may want to limit the API usage of each user to be at most 100 API calls within a period of 10 minutes. If too many requests are received from a user within the stated period of the time, a response with status code 429 (meaning "Too Many Requests") should be returned.

use Yiisoft\Yii\RateLimiter\Middleware;
use Yiisoft\Yii\RateLimiter\Counter;
use Yiisoft\Cache\ArrayCache;
use Nyholm\Psr7\Factory\Psr17Factory;

$cache = new ArrayCache();
$counter = new Counter(2, 5, $cache);
$responseFactory = new Psr17Factory();

$middleware = new Middleware($counter, $responseFactory);

In the above 2 is the maximum number of increments that could be performed before increments are limited and 5 is a period to apply limit to, in seconds.

The Counter implements generic cell rate limit algorithm (GCRA) that ensures that after reaching the limit further increments are distributed equally.

Note: While it is sufficiently effective, it is preferred to use Nginx or another webserver capabilities for rate limiting. This package allows rate-limiting in the project with deployment environment you cannot control such as installable CMS.