nadylib / leaky-bucket
基于纤维的LeakyBucket算法实现
0.1.0
2024-04-28 12:54 UTC
Requires
- php: >=8.1.17
- psr/log: ^1|^2|^3
- revolt/event-loop: ^1.0
Requires (Dev)
- composer-phar/php-cs-fixer: ^3.51.0
- composer-phar/phpstan: ^1.10
- nadybot/nadystyle: ^1.0
- phpunit/phpunit: ^10.0
- squizlabs/php_codesniffer: ^3.8
- thecodingmachine/phpstan-safe-rule: ^1.2
README
使用Revolt EventLoop实现的异步LeakyBucket实现
用法
use Nadylib\LeakyBucket\LeakyBucket; $bucket = new Nadylib\LeakyBucket\LeakyBucket( size: 5, refillDelay: 1.0, refillAmount: 1 );
只有一个感兴趣的功能:LeakyBucket::take(<数量>)
use Nadylib\LeakyBucket\LeakyBucket; $bucket = new Nadylib\LeakyBucket\LeakyBucket( size: 5, refillDelay: 1.0, refillAmount: 1 ); for ($i = 1; $i <= 7; $i++) { $bucket->take(1); $time = (new DateTimeImmutable())->format("H:i:s.v"); echo("[{$time}] Taken.\n"); }
前5次调用将立即执行,第6次和第7次调用各需1秒。没有睡眠,只有异步纤维,所以这绝对安全使用。
use Nadylib\LeakyBucket\LeakyBucket; use Revolt\EventLoop; $bucket = new Nadylib\LeakyBucket\LeakyBucket( size: 5, refillDelay: 1.0, refillAmount: 1 ); for ($i = 1; $i <= 7; $i++) { $bucket->take(callback: function() { $time = (new DateTimeImmutable())->format("H:i:s.v"); echo("[{$time}] Taken.\n"); }); } EventLoop::run();
这的行为完全相同,但是对$bucket->take()
的调用将始终立即返回。
当使用回调版本时,确保在最后调用EventLoop::run()
,因为主纤维/线程永远不会挂起,而是始终立即返回,所以你必须确保事件循环完成其工作。在现实世界环境中,这通常是不必要的,因为你的代码无论如何都会在全局事件循环中运行。