定制 detain/rate-limit 二次开发

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

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

detain/rate-limit

Composer 安装命令:

composer require detain/rate-limit

包简介

PHP rate limiting library with Token Bucket and Leaky Bucket Algorithms, based on palepurple/rate-limit, grandson to touhonoob/rate-limit, and jeroenvisser101/LeakyBucket

README 文档

README

GitHub Build Travis Build Coverage Status Code Climate Scrutinizer Code Quality Codacy Badge

Latest Stable Version Total Downloads Latest Unstable Version License Monthly Downloads Daily Downloads

PHP Rate Limiting library with both Token Bucket and Leaky Bucket Algorithms, minimal external dependencies, and many storage backends.

Algorithms

  • Token Bucket Algorithm Token Bucket is an algorithm which works as follows:

    • There is a bucket.
    • A token is added to the bucket every 1/r seconds.
    • The bucket can hold at the most b tokens. If a token arrives when the bucket is full, it is discarded.
    • When a packet (network layer PDU) of n bytes arrives,
      • If at least n tokens are in the bucket, n tokens are removed from the bucket, and the packet is sent to the network.
      • if fewer than n tokens are available, no tokens are removed from the bucket, and the packet is considered to be non-conformant.
  • Leaky Bucket Algorithm Leaky Bucket is an algorithm which works as follows:

    • There is a bucket.
    • The bucket has a defined leak and defined capacity.
    • The bucket leaks at a constant rate.
    • Overflows when full, will not add other drops to the bucket.

Storage Adapters

The RateLimiter needs to know where to get/set data.

Depending on which adapter you install, you may need to install additional libraries (predis/predis or tedivm/stash) or PHP extensions (e.g. Redis, Memcache, APCu)

Installing via Composer

curl -sS https://getcomposer.org/installer | php
composer.phar require detain/rate-limit

Usage

Token Bucket

require 'vendor/autoload.php';

use \Detain\RateLimit\RateLimit;
use \Detain\RateLimit\Adapter\APCu as APCAdapter;
use \Detain\RateLimit\Adapter\Redis as RedisAdapter;
use \Detain\RateLimit\Adapter\Predis as PredisAdapter;
use \Detain\RateLimit\Adapter\Memcached as MemcachedAdapter;
use \Detain\RateLimit\Adapter\Stash as StashAdapter;


$adapter = new APCAdapter(); // Use APC as Storage
// Alternatives:
//
// $adapter = new RedisAdapter((new \Redis()->connect('localhost'))); // Use Redis as Storage
//
// $adapter = new PredisAdapter(new \Predis\Predis(['tcp://127.0.0.1:6379'])); // Use Predis as Storage
//
// $memcache = new \Memcached();
// $memcache->addServer('localhost', 11211);
// $adapter = new MemcacheAdapter($memcache); 
//
// $stash = new \Stash\Pool(new \Stash\Driver\FileSystem());
// $adapter = new StashAdapter($stash);

$rateLimit = new RateLimit("myratelimit", 100, 3600, $adapter); // 100 Requests / Hour

$id = $_SERVER['REMOTE_ADDR']; // Use client IP as identity
if ($rateLimit->check($id)) {
  echo "passed";
} else {
  echo "rate limit exceeded";
}

Leaky Bucket

Basic usage

<?php

use \Detain\RateLimit\LeakyBucket;
use \Detain\RateLimit\Adapter\Redis as RedisAdapter;

$adapter = new RedisAdapter((new \Redis()->connect('localhost'))); // Use Redis as Storage

// Define the bucket
$settings = [
	'capacity' => 10,
	'leak'     => 1
];

// Create the bucket
$bucket = new LeakyBucket('example-bucket', $storage, $settings);

// Fill the bucket
$bucket->fill();

// Check if it's full
if ($bucket->isFull()) {
	header('HTTP/1.1 429 Too Many Requests');
	exit '<!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>';
}

// ...

Other functionality

You can also do great stuff with it through the methods that LeakyBucket provides.

// 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
	]
);

// Get 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();

References

Continuation or Expansion of these Projects

Knowledge

PSR-7 Middleware Handlers to Base the Future PSR7 Support Off Of

  • nikolaposa/rate-limit 🚔 Standalone component that facilitates rate-limiting functionality. Also provides a middleware designed for API and/or other application endpoints.
  • robwittman/leaky-bucket-rate-limiter PSR-7 Leaky Bucket Rate Limiter - This middleware enables API Rate-Limiting based on a Leaky Bucket algorithm.

detain/rate-limit 适用场景与选型建议

detain/rate-limit 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 2.05k 次下载、GitHub Stars 达 2, 最近一次更新时间为 2020 年 03 月 19 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「throttling」 「ratelimit」 「limits」 「leakybucket」 「tokenbucket」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 detain/rate-limit 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 detain/rate-limit 我们能提供哪些服务?
定制开发 / 二次开发

基于 detain/rate-limit 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 2.05k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 2
  • 点击次数: 6
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 2
  • Watchers: 0
  • Forks: 26
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2020-03-19