michaelesmith/throttle

0.2.0 2018-11-06 05:22 UTC

This package is auto-updated.

Last update: 2024-09-18 05:03:59 UTC


README

Build Status

这是什么?

基本节流实现

版本

如果你在寻找与PHP 5.3兼容的旧版本,请尝试v0.1分支,并将你的composer需求更新为"michaelesmith/throttle": "^0.1"

安装

composer require "michaelesmith/throttle"

你还需要一个PSR-6兼容的缓存库,例如 "cache/cache""symfony/cache"

示例

$throttle = new Throttle(new \Cache\Adapter\PHPArray\ArrayCachePool());
$throttle->add(new Condition(60, 2)); // adds an interval where 2 increments are allowed in 60 seconds
$throttle->add(new Condition(600, 5)); // adds an interval where 5 increments are allowed in 10 minutes

// in each action you want to limit
try {
    $throttle->increment($_SERVER['REMOTE_ADDR']); // some client identifier like an ip or session id
    // NOTE: $_SERVER['REMOTE_ADDR'] may not gove you the actual client IP if you are behind a reverse proxy
    // Here is how Symfony finds the client IP
    // @link: https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/Request.php#L786-L805
} catch(RateException $e) {
    $condition = $e->getCondition(); // the condition that hit the rate limit
    printf('You can only make %d requests in %d seconds', $condition->getLimit(), $condition->getTtl());
}

你可以使用任何PSR-6兼容的缓存池,但大多数情况下你需要使用一个可以在请求间持久化的缓存,而不是像这个示例一样。