PHP
Rate Limiter - Token Bucket Algorithm
تنفيذ متقدم لـ Rate Limiter باستخدام Token Bucket Algorithm. يدعم Burst requests وdistributed systems.
class TokenBucketRateLimiter {
private int $capacity;
private float $refillRate;
private array $buckets = [];
private $storage; // Redis or Cache
public function __construct(int $capacity, float $refillRate, $storage = null) {
$this->capacity = $capacity;
$this->refillRate = $refillRate; // tokens per second
$this->storage = $storage;
}
public function isAllowed(string $key, int $tokens = 1): bool {
$bucket = $this->getBucket($key);
$now = microtime(true);
// Refill tokens
$tokensToAdd = ($now - $bucket['lastRefill']) * $this->refillRate;
$bucket['tokens'] = min(
$this->capacity,
$bucket['tokens'] + $tokensToAdd
);
$bucket['lastRefill'] = $now;
// Check if enough tokens
if ($bucket['tokens'] >= $tokens) {
$bucket['tokens'] -= $tokens;
$this->saveBucket($key, $bucket);
return true;
}
$this->saveBucket($key, $bucket);
return false;
}
private function getBucket(string $key): array {
if ($this->storage) {
$data = $this->storage->get("rate_limit:{$key}");
return $data ? json_decode($data, true) : $this->newBucket();
}
return $this->buckets[$key] ?? $this->newBucket();
}
private function newBucket(): array {
return [
'tokens' => $this->capacity,
'lastRefill' => microtime(true)
];
}
private function saveBucket(string $key, array $bucket): void {
if ($this->storage) {
$this->storage->setex(
"rate_limit:{$key}",
3600,
json_encode($bucket)
);
} else {
$this->buckets[$key] = $bucket;
}
}
public function getRemaining(string $key): int {
$bucket = $this->getBucket($key);
return (int) floor($bucket['tokens']);
}
}
// Usage
$limiter = new TokenBucketRateLimiter(100, 10); // 100 tokens, 10/sec refill
if ($limiter->isAllowed('user:123', 5)) {
// Process request
} else {
// Rate limit exceeded
}
💡 مثال الاستخدام
استخدم Rate Limiter لحماية APIs من Abuse، توزيع الحمل، أو التحكم في استخدام الموارد.
استخدام حر
هذا الكود متاح للاستخدام الحر. إذا كان لديك أسئلة أو تحتاج مساعدة، لا تتردد في التواصل معي.