razonyang/yii2-rate-limiter

Yii2 Rate Limiter

Installs: 15 239

Dependents: 1

Suggesters: 0

Security: 0

Stars: 9

Watchers: 4

Forks: 0

Open Issues: 0

Type:yii2-extension

1.0.0 2019-08-21 04:46 UTC

This package is auto-updated.

Last update: 2024-05-21 20:06:37 UTC


README

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

Backends

Installation

composer require razonyang/yii2-rate-limiter

Usage

Let's take 5000 requests every hours as example:

return [
    public function behaviors()
    {
        return [
            // redis via redis extension
            'rateLimiter' => [
                'class' => \RazonYang\Yii2\RateLimiter\RedisRateLimiter::class,
                'password' => '',
                'hostname' => 'localhost',
                'port' => 6379,
                'capacity' => 5000,
                'rate' => 0.72,
                'limitPeriod' => 3600,
                'prefix' => 'rate_limiter:',
                'ttl' => 3600,
                // 'nameCallback' => $callback,
            ],
            // redis via yii2-redis
            'rateLimiter' => [
                'class' => \RazonYang\Yii2\RateLimiter\Redis\RateLimiter::class,
                'redis' => 'redis', // redis component name or definition
                'capacity' => 5000,
                'rate' => 0.72,
                'limitPeriod' => 3600,
                'prefix' => 'rate_limiter:',
                'ttl' => 3600,
                // 'nameCallback' => $callback,
            ],

            // memcached
            'rateLimiter' => [
                'class' => \RazonYang\Yii2\RateLimiter\MemcachedRateLimiter::class,
                'hostname' => 'localhost',
                'port' => 11211,
                'capacity' => 5000,
                'rate' => 0.72,
                'limitPeriod' => 3600,
                'prefix' => 'rate_limiter:',
                'ttl' => 3600,
                // 'nameCallback' => $callback,
            ],
        ];
    }
];

RateLimiter takes uid:route(authorized) or ip:route(guest) as bucket name, you can also change this behavior via nameCallback:

$nameCallback = function (
    \yii\web\User $user,
    \yii\web\Request $request,
    \yii\base\Action $action
): string {
    return 'bucket name';
}