当前位置: 首页 > news >正文

PHP流量控制令牌桶算法

<?php
class TrafficController {private $capacity; // 桶的容量private $rate; // 每秒产生的令牌数private $tokens; // 当前桶中的令牌数private $lastRefillTime; // 上次填充令牌的时间private $waitingRequests; // 等待的请求队列private $counters; // 用户访问计数器public function __construct($capacity, $rate) {$this->capacity = $capacity;$this->rate = $rate;$this->tokens = $capacity;$this->lastRefillTime = time();$this->waitingRequests = [];$this->counters = [];}public function allowRequest($userId) {$this->refillTokens();if ($this->tokens < 1 || $this->exceedsRateLimit($userId)) {$this->waitingRequests[$userId][] = time();return false; // 请求被限流}$this->tokens--;$this->counters[$userId]++;return true; // 可以处理请求}private function refillTokens() {$currentTime = time();$this->tokens = min($this->capacity,$this->tokens + ($currentTime - $this->lastRefillTime) * $this->rate);$this->lastRefillTime = $currentTime;}private function exceedsRateLimit($userId) {$count = $this->counters[$userId] ?? 0;return $count >= $this->rate;}
}// 使用示例
$trafficController = new TrafficController(10, 2); // 桶容量为10,每秒产生2个令牌// 用户A发起请求
$userIdA = 1;
if ($trafficController->allowRequest($userIdA)) {// 处理请求echo "处理请求";
} else {// 请求被限流,返回错误信息echo "请求被限流";
}// 用户B发起请求
$userIdB = 2;
if ($trafficController->allowRequest($userIdB)) {// 处理请求echo "处理请求";
} else {// 请求被限流,返回错误信息echo "请求被限流";
}
?>

  

http://www.rkmt.cn/news/1409.html

相关文章:

  • 顽固文件夹无法删除?
  • c++ std::map
  • 软考架构备考-面向对象
  • 【Python】Word文档解析表格并导出Excel
  • 2025.9.9 总结
  • 2025 9 6 总结
  • OLE读取EXCEL内容
  • Rope pbds
  • 25.9.8随笔联考总结
  • IT 失业人员的福音:借微软 Dynamics 365 CRM 与 Power Platform 快速重启职业生涯
  • 测试
  • 0124_观察者模式(Observer)
  • 洛谷P5854 【模板】笛卡尔树 题解 笛卡尔树模板题
  • 都江堰操作系统
  • [OLAP/Doris] Doris 之表设计
  • 20250909 之所思 - 人生如梦
  • 认识人工智能-基础认知
  • 苹果im虚拟机协议群发系统,苹果imessage推信软件,苹果iMessage自动群发协议–持续更新中...
  • 课前问题思考1
  • huggingface
  • 从0到1实现Transformer模型-CS336作业1
  • Morpheus 审计报告分享:AAVE 项目 Pool 合约地址更新导致的组合性风险
  • U3D动作游戏开发读书笔记--2.1一些通用的预备知识
  • Word中VBA提取人名所在的页码
  • ARC
  • Ubuntu 安装 Git
  • systemctl命令
  • 知识蒸馏
  • 第一次学dij qwq(p4779
  • 2025—2026 赛季记录