use bandwidthThrottle\tokenBucket\Rate;
use bandwidthThrottle\tokenBucket\TokenBucket;
use bandwidthThrottle\tokenBucket\storage\FileStorage;
$storage = new FileStorage(__DIR__ . "/api.bucket");
$rate = new Rate(10, Rate::SECOND);
$bucket = new TokenBucket(10, $rate, $storage);
$bucket->bootstrap(10);
if (!$bucket->consume(1, $seconds)) {
http_response_code(429);
header(sprintf("Retry-After: %d", floor($seconds)));
exit();
}
Show file
Open project: bandwidth-throttle/token-bucket
Class Usage Examples
Method | Description | |
---|---|---|
__construct ( integer $capacity, |
Initializes the Token bucket. | |
bootstrap ( integer $tokens ) | Bootstraps the storage with an initial amount of tokens. | |
consume ( integer $tokens, &$seconds ) : boolean | Consumes tokens from the bucket. | |
getCapacity ( ) : integer | The token capacity of this bucket. | |
getRate ( ) : |
Returns the token add rate. | |
getTokens ( ) : integer | Returns the currently available tokens of this bucket. |
Method | Description | |
---|---|---|
loadTokensAndTimestamp ( ) : array | Loads the stored timestamp and its respective amount of tokens. |
public __construct ( integer $capacity, |
||
$capacity | integer | positive capacity of the bucket |
$rate | rate | |
$storage | bandwidthThrottle\tokenBucket\storage\Storage | storage |
public getCapacity ( ) : integer | ||
return | integer | The capacity. |