Leaky Bucket算法的实现。
v0.21
2017-04-05 21:46 UTC
Requires
- php: >=5.4.0
Requires (Dev)
- phpunit/phpunit: 4.1.*
- predis/predis: >=0.8.0
Suggests
- ext-memcached: Needed for Memcached based backend.
- predis/predis: Needed for Redis based backend.
This package is not auto-updated.
Last update: 2024-09-20 20:10:58 UTC
README
Leaky Bucket算法工作原理如下:
- 有一个桶。
- 桶具有定义的泄漏率和容量。
- 桶以恒定速率泄漏。
- 当桶满时,将不会向桶中添加更多水滴。
安装
php composer.phar require "pskuza/leakybucket"
使用方法
基本使用
<?php use LeakyBucket\LeakyBucket; use LeakyBucket\Storage\RedisStorage; // Define which storage to use $storage = new RedisStorage(); // Define the bucket $settings = [ 'capacity' => 10, 'leak' => 1 ]; // Create the bucket $bucket = new LeakyBucket('example-bucket', $storage, $settings); // Fill the bucket $bucket->fill(); $bucket->save(); // Check if it's full if ($bucket->isFull()) { header('HTTP/1.1 429 Too Many Requests'); die('<!doctype html><html><body><h1>429 Too Many Requests</h1><p>You seem to be doing a lot of requests. You\'re now cooling down.</p></body></html>'); } // ...
对于memcached使用
<?php use LeakyBucket\LeakyBucket; use LeakyBucket\Storage\MemcachedStorage; // Define which storage to use $storage = new MemcachedStorage();
其他功能
您还可以通过LeakyBucket提供的方法做更多精彩的事情。
// Get capacity information $capacityTotal = $bucket->getCapacity(); $capacityLeft = $bucket->getCapacityLeft(); $capacityUsed = $bucket->getCapacityUsed(); // Get the drops/second that the bucket leaks $leakPerSecond = $bucket->getLeak(); // Get the last timestamp from when the bucket was updated $timestamp = $bucket->getLastTimestamp(); // Set additional data $bucket->setData( [ 'timeout' => 3600 ] ); // Set additional data $data = $bucket->getData(); // Update the bucket with the leaked drops $bucket->leak(); // Remove excess drops $bucket->overflow(); // Update the bucket's timestamp manually $bucket->touch(); // Fill the bucket with one drop $bucket->fill(); // Fill the bucket with 5 drops $bucket->fill(5); // Spill one drop from the bucket $bucket->spill(); // Spill 5 drops from the bucket $bucket->spill(5); // Remove the bucket's content $bucket->reset(); // Force save $bucket->save();
贡献
您可以通过fork仓库并创建pull请求来贡献。您还可以创建问题或功能请求。
清单
- 您的代码符合PSR-2标准。(使用php-cs-checker进行检查)
- 您的代码经过完全测试,并提供了PHPUnit测试。
- 您的代码通过了TravisCI构建。
- 通过贡献代码,您同意将您的贡献许可在MIT许可证下。
无聊的法律事宜
本项目采用MIT许可证。在仓库中可以找到LICENSE文件。