PHP code example of cjphp / rate-limiter
1. Go to this page and download the library: Download cjphp/rate-limiter library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
cjphp / rate-limiter example snippets
use RateLimiter\RateLimiter;
use RateLimiter\StorageFactory;
use RateLimiter\StrategyFactory;
$key = 'user_123';
$storeType = 'file'; // file | redis
$strategyType = 'fixed_window'; // fixed_window | sliding_window | leaky_bucket
$params = [
'limit' => 10, // 窗口内最大请求数(固定/滑动窗口)
'window' => 60, // 窗口大小,秒
'rate' => 1, // 漏桶:每秒漏出 1 个请求
'capacity' => 3, // 漏桶:桶容量 3
];
$ext = match ($storeType) {
'file' => sys_get_temp_dir() . '/ratelimit',
'redis' => $redis, // \Redis 已连接实例
};
$storage = StorageFactory::create($storeType, $ext);
$strategy = StrategyFactory::create($strategyType, $storage, $params);
// 注意:RateLimiter 与 Strategy 必须使用同一 $storage 实例
$rateLimiter = new RateLimiter($storage, $strategy);
if ($rateLimiter->isRateLimited($key, false)) {
echo '不好意思,您被流控了';
} else {
echo '允许通行';
}
rate-limiter/
├── src/
│ ├── RateLimiter.php
│ ├── StorageFactory.php
│ ├── StrategyFactory.php
│ ├── Exception/
│ │ └── RateLimitException.php
│ ├── Storage/
│ │ ├── StorageInterface.php
│ │ ├── FileStorage.php
│ │ └── RedisStorage.php
│ └── Strategy/
│ ├── StrategyInterface.php
│ ├── FixedWindowStrategy.php
│ ├── SlidingWindowStrategy.php
│ └── LeakyBucketStrategy.php
├── tests/
├── composer.json
├── phpunit.xml
└── README.md