定制 xp-forge/ratelimit 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

xp-forge/ratelimit

最新稳定版本:v3.2.0

Composer 安装命令:

composer require xp-forge/ratelimit

包简介

Rate limiting

关键字:

README 文档

README

Build status on GitHub XP Framework Module BSD Licence Requires PHP 7.0+ Supports PHP 8.0+ Latest Stable Version

A rate limiting can be used to limit the rate at which physical or logical resources are accessed, e.g. to protect them from intentional or unintentional overuse.

Restricting usage

Imagine you don't want to run more than two tasks per second:

use util\invoke\RateLimiting;

$rateLimiter= new RateLimiting(2);
foreach ($tasks as $task) {
  $rateLimiter->acquire();    // will wait if necessary
  $task->run();
}

Restricting bandwidth

You can implement bandwidth throttling by acquiring a permit for each byte:

use util\invoke\{RateLimiting, Rate, Per};

$rateLimiter= new RateLimiting(new Rate(1000000, Per::$MINUTE));
while ($bytes= $source->read()) {
  $rateLimiter->acquire(strlen($bytes));
  $target->write($bytes);
}

Rate-limiting users

Implement a filter like the following:

use web\{Filter, Error};
use util\invoke\{RateLimiting, Rate, Per};

class RateLimitingFilter implements Filter {
  private $rates, $rate, $timeout;

  public function __construct(KeyValueStorage $rates) {
    $this->rates= $rates;
    $this->rate= new Rate(5000, Per::$HOUR);
    $this->timeout= 0.2;
  }

  public function filter($request, $response, $invocation) {
    $remote= $request->header('Remote-Addr');

    $limits= $this->rates->get($remote) ?: new RateLimiting($this->rate);
    $permitted= $limits->tryAcquiring(1, $this->timeout);
    $this->rates->put($remote, $limits);

    $response->header('X-RateLimit-Limit', $limits->rate()->value());
    $response->header('X-RateLimit-Remaining', $limits->remaining());
    $response->header('X-RateLimit-Reset', $limits->resetTime());

    if (!$permitted) {
      throw new Error(429, 'Rate limit exceeded');
    }

    return $invocation->proceed($request, $response);
  }
}

Further reading

统计信息

  • 总下载量: 17
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 1
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: BSD-3-Clause
  • 更新时间: 2015-01-10

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固