alphavel/rate-limit 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

alphavel/rate-limit

最新稳定版本:v1.0.0

Composer 安装命令:

composer require alphavel/rate-limit

包简介

High-performance rate limiting for Alphavel using Swoole Table

README 文档

README

High-performance rate limiting package for Alphavel Framework using Swoole Table.

Features

  • 0.001ms latency (1000x faster than Redis)
  • 🚀 Zero dependencies (Swoole built-in)
  • 🔒 Thread-safe (atomic operations)
  • 💾 Shared memory between workers
  • 🎯 Multiple levels (IP, User, Endpoint, Global)
  • 🛡️ DDoS protection (global rate limiting)
  • 📊 CLI tools (stats, list, reset, block)

Performance

Baseline (no rate limit):  5,042 req/s
With rate limit:            5,038 req/s
Overhead:                   0.08% (negligible)

Installation

composer require alphavel/rate-limit

Configuration

Publish configuration:

php alpha vendor:publish --tag=rate-limit-config

Configure .env:

RATE_LIMIT_DRIVER=swoole
RATE_LIMIT_MAX_ENTRIES=100000
RATE_LIMIT_DEFAULT=1000
RATE_LIMIT_WINDOW=60
RATE_LIMIT_ENABLE_GLOBAL=false
RATE_LIMIT_GLOBAL=10000

Usage

Basic Usage

// routes/api.php

// 100 requests per minute per IP
$router->middleware('rate_limit:100,60,ip')->group(function ($router) {
    $router->post('/auth/login', [AuthController::class, 'login']);
});

// 1000 requests per minute per authenticated user
$router->middleware(['auth', 'rate_limit:1000,60,user'])->group(function ($router) {
    $router->get('/users', [UserController::class, 'index']);
});

// 10 requests per minute per IP on this specific endpoint
$router->middleware('rate_limit:10,60,endpoint')->post('/heavy-operation', [Controller::class, 'heavy']);

Multiple Levels (Defense in Depth)

$router->middleware([
    'rate_limit:1000,60,ip',      // 1000/min per IP
    'rate_limit:100,60,user',      // 100/min per user
    'rate_limit:10,60,endpoint'    // 10/min on this endpoint
])->post('/ai/generate', [AIController::class, 'generate']);

Available Levels

  • ip - Rate limit by IP address
  • user - Rate limit by authenticated user ID
  • api_key - Rate limit by API key (X-API-Key header)
  • endpoint - Rate limit by IP + endpoint path
  • session - Rate limit by session ID
  • global - Global rate limit (DDoS protection)

CLI Commands

Show Statistics

php alpha rate-limit:stats

List Active Limits

php alpha rate-limit:list

# Show only blocked entries
php alpha rate-limit:list --blocked

Reset Rate Limit

php alpha rate-limit:reset ip:192.168.1.1

Block IP/User

# Block for 1 hour (default)
php alpha rate-limit:block ip:192.168.1.1

# Block for specific duration
php alpha rate-limit:block ip:192.168.1.1 --duration=3600

Whitelist

Add trusted IPs to whitelist (never rate limited):

// config/rate_limit.php

'whitelist' => [
    '127.0.0.1',
    '::1',
    '10.0.0.0/8',        // Private network
    '192.168.1.100',     // Load balancer
],

Global Rate Limit (DDoS Protection)

Enable global rate limiting to protect against DDoS:

RATE_LIMIT_ENABLE_GLOBAL=true
RATE_LIMIT_GLOBAL=10000  # 10k requests/second globally

This is applied before individual rate limits.

Response Headers

Rate limit information is included in response headers:

HTTP/1.1 200 OK
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1700000000

When rate limit is exceeded:

HTTP/1.1 429 Too Many Requests
Retry-After: 42
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1700000042

{
  "error": "rate_limit_exceeded",
  "message": "Rate limit of 100 requests per minute exceeded for your IP.",
  "retry_after": 42,
  "reset_at": 1700000042
}

Memory Usage

Swoole Table memory calculation:

  • 16 bytes per entry
  • 100k entries = 1.6 MB
  • 1M entries = 16 MB

Configure based on your needs:

// config/rate_limit.php

'swoole' => [
    'max_entries' => 100000, // Adjust based on unique IPs/users expected
],

Bootstrap (Important!)

Initialize Swoole Table before $server->start():

// bootstrap/server.php

use Alphavel\RateLimit\Drivers\SwooleTableDriver;

// Initialize BEFORE server start
SwooleTableDriver::init(config('rate_limit.swoole.max_entries', 100000));

$server->start();

Testing

composer test

Benchmarking

# Without rate limiting
wrk -t4 -c100 -d20s http://localhost:8087/api/test

# With rate limiting
wrk -t4 -c100 -d20s http://localhost:8087/api/test-limited

Requirements

  • PHP >= 8.1
  • Swoole Extension >= 5.0
  • Alphavel Framework >= 1.0

License

MIT License - see LICENSE file for details.

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-11-22

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固