1. Go to this page and download the library: Download kode/limiting 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/ */
use Kode\Limiting\Enum\FailurePolicy;
use Kode\Limiting\Store\RedisStore;
use Kode\Limiting\Store\ResilientStore;
use Kode\Limiting\Limiter;
// 默认 fail-open:存储宕机时放行,并把结果标记为降级态
$safe = new ResilientStore(RedisStore::create(), FailurePolicy::ALLOW);
$result = Limiter::tokenBucket(100, 10.0, $safe)->consume('api:user:1');
if ($result->degraded) {
// 降级放行:记录告警,但请求照常通过
error_log('限流器降级:' . $result->degradedReason);
}
// 严格模式:存储故障时原样抛出 StoreException
$strict = new ResilientStore(RedisStore::create(), FailurePolicy::RETHROW);
use Kode\Limiting\EventHandler\LimiterEventHandler;
use Kode\Limiting\DTO\LimiterResult;
$handler = new class implements LimiterEventHandler {
public function onResult(string $key, LimiterResult $result): void {
if ($result->degraded) { /* 上报降级 */ }
}
public function onError(string $key, \Throwable $error): void {
/* 上报异常 */
}
};
Limiter::tokenBucket(100, 10.0)->withEventHandler($handler)->consume('api:user:1');
public function get(string $key): ?string; // 获取值
public function set(string $key, string $value, int $ttl = 0): void; // 设置值,ttl=0 不过期
public function delete(string $key): void; // 删除键
public function incr(string $key, int $step = 1, int $ttl = 0): int; // 原子递增
public function decr(string $key, int $step = 1): int; // 原子递减
public function ttl(string $key): int; // 剩余 TTL(>=0 / -1 永不过期 / -2 不存在)
public function has(string $key): bool; // 键是否存在且未过期
public function allow(string $key, int $tokens = 1): bool; // 是否放行
public function check(string $key, int $tokens = 1): LimiterResult; // 只读探测
public function consume(string $key, int $tokens = 1): LimiterResult; // 消耗并返回结果
public function getRemaining(string $key): float; // 剩余额度
public function getWaitTime(string $key): float; // 建议等待秒数
public function reset(string $key): void; // 重置
public function getCapacity(): int; // 总额度
use Kode\Limiting\Store\StoreInterface;
class MyStore implements StoreInterface
{
public function get(string $key): ?string { /* ... */ }
public function set(string $key, string $value, int $ttl = 0): void { /* ... */ }
public function delete(string $key): void { /* ... */ }
public function incr(string $key, int $step = 1, int $ttl = 0): int { /* ... */ }
public function decr(string $key, int $step = 1): int { /* ... */ }
public function ttl(string $key): int { /* ... */ }
public function has(string $key): bool { /* ... */ }
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.