godsdev / rate-limiter-mysql
godsdev/rate-limiter-interface 的 MySQL 实现
v0.1.0
2017-07-07 20:28 UTC
Requires
- php: >=5.6
- beberlei/assert: ^2.7
- godsdev/rate-limiter-interface: ^0.1.1
Requires (Dev)
- phpunit/phpunit: ^4|^5
This package is auto-updated.
Last update: 2024-09-25 00:18:19 UTC
README
MySQL 请求速率限制器实现 ---------------------------------------------.
使用 https://github.com/GodsDev/rate-limiter-interface
配置
$conn = \GodsDev\RateLimiter\RateLimiterMysql::createConnectionObj($dbConfig); $limiter = new \GodsDev\RateLimiter\RateLimiterMysql( $rate, //int $period, //int $userId, //string $conn // \PDO connection );
为了避免 PHP 和 MySQL 中设置的不同时间造成的问题(例如,每次击中后计数重置)
//@todo put into PHPUnit test instead! $stmt = $conn->prepare("SELECT NOW();"); $stmt->execute(); $row = $stmt->fetch(); $timestampPhp = date("Y-m-d H:i:s"); if($row[0] !== $timestampPhp){ error_log("MySQL time {$row[0]} is different from PHP {$timestampPhp}"); } //in case of identified troubles fix by some code like this date_default_timezone_set('Europe/Prague'); /** or directly in php.ini [Date] date.timezone = "Europe/Prague" **/
用法
//For quota notification calculation $consumedFromThePast = $limiter->getHits($timestamp); //Increments usage in time and returns number of hits allowed (compared to increment) $consumedAmount = $limiter->inc($timestamp, $wantToConsumeAmount); if ($consumedAmount < 1) { // you must wait } else if ($wantToConsumeAmount > $consumedAmount) { // it may partly be executed } else { // green go }
默认表名为 rate_limiter
,在调用限制器构造函数时可能被更改。其结构在 sql/rate_limiter.sql
中描述。
测试
为了使 ./test-mysql.sh
的工作,必须创建一个包含有效数据库连接的本地文件 config.local.php
。其语法为
$config["dbConnection"] = array( //if you can, use localhost instead of 127.0.0.1 to speed up access on Linux. see a comment in https://php.ac.cn/manual/en/pdo.connections.php "dsn" => "mysql:dbname=rate_limiter_test;host=localhost", "user" => "root", "pass" => "", );