当前位置:首页 > PHP

php实现限流

2026-01-29 19:25:24PHP

PHP 实现限流的方法

计数器法

计数器法是最简单的限流算法,通过统计单位时间内的请求次数来判断是否超过阈值。

class CounterLimiter {
    private $limit;
    private $interval;
    private $count = 0;
    private $lastResetTime;

    public function __construct($limit, $interval) {
        $this->limit = $limit;
        $this->interval = $interval;
        $this->lastResetTime = time();
    }

    public function allowRequest() {
        $currentTime = time();
        if ($currentTime - $this->lastResetTime > $this->interval) {
            $this->count = 0;
            $this->lastResetTime = $currentTime;
        }
        if ($this->count < $this->limit) {
            $this->count++;
            return true;
        }
        return false;
    }
}

滑动窗口法

滑动窗口法是对计数器法的改进,可以更精确地控制单位时间内的请求量。

php实现限流

class SlidingWindowLimiter {
    private $limit;
    private $interval;
    private $requests = [];

    public function __construct($limit, $interval) {
        $this->limit = $limit;
        $this->interval = $interval;
    }

    public function allowRequest() {
        $currentTime = time();
        $this->requests[] = $currentTime;
        while (!empty($this->requests) && $currentTime - $this->requests[0] > $this->interval) {
            array_shift($this->requests);
        }
        return count($this->requests) <= $this->limit;
    }
}

令牌桶算法

令牌桶算法允许突发流量,通过定期向桶中添加令牌来控制请求速率。

php实现限流

class TokenBucketLimiter {
    private $capacity;
    private $tokens;
    private $rate;
    private $lastTime;

    public function __construct($capacity, $rate) {
        $this->capacity = $capacity;
        $this->tokens = $capacity;
        $this->rate = $rate;
        $this->lastTime = time();
    }

    public function allowRequest() {
        $currentTime = time();
        $elapsed = $currentTime - $this->lastTime;
        $this->tokens = min($this->capacity, $this->tokens + $elapsed * $this->rate);
        $this->lastTime = $currentTime;
        if ($this->tokens >= 1) {
            $this->tokens--;
            return true;
        }
        return false;
    }
}

Redis 实现分布式限流

在分布式环境中,可以使用 Redis 实现限流,确保多个服务节点之间的限流一致性。

class RedisLimiter {
    private $redis;
    private $key;
    private $limit;
    private $interval;

    public function __construct($redis, $key, $limit, $interval) {
        $this->redis = $redis;
        $this->key = $key;
        $this->limit = $limit;
        $this->interval = $interval;
    }

    public function allowRequest() {
        $currentTime = time();
        $this->redis->zRemRangeByScore($this->key, 0, $currentTime - $this->interval);
        $count = $this->redis->zCard($this->key);
        if ($count < $this->limit) {
            $this->redis->zAdd($this->key, $currentTime, uniqid());
            return true;
        }
        return false;
    }
}

使用框架中间件

在 Laravel 等框架中,可以使用中间件实现限流功能。

namespace App\Http\Middleware;

use Closure;
use Illuminate\Cache\RateLimiter;
use Symfony\Component\HttpFoundation\Response;

class ThrottleRequests {
    protected $limiter;

    public function __construct(RateLimiter $limiter) {
        $this->limiter = $limiter;
    }

    public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1) {
        $key = $request->ip();
        if ($this->limiter->tooManyAttempts($key, $maxAttempts)) {
            return new Response('Too Many Attempts', 429);
        }
        $this->limiter->hit($key, $decayMinutes * 60);
        return $next($request);
    }
}

以上方法可以根据实际需求选择适合的限流策略,单机环境下可以使用内存限流,分布式环境下建议使用 Redis 实现。

标签: php
分享给朋友:

相关文章

php实现表单

php实现表单

PHP 表单基础实现 创建一个简单的 PHP 表单需要 HTML 表单结构和 PHP 处理脚本。以下是一个完整的示例: HTML 表单部分 (form.html) <form action=…

php 登录实现

php 登录实现

PHP 登录实现 PHP 登录功能通常包括用户认证、会话管理和安全性措施。以下是实现 PHP 登录功能的关键步骤。 数据库准备 创建一个用户表存储用户信息,通常包括用户名、密码(加密存储)和其他必要…

php 实现接口

php 实现接口

PHP 实现接口的方法 在 PHP 中,接口(Interface)用于定义一组方法的规范,而不包含具体的实现。类可以实现(implement)接口,并必须实现接口中定义的所有方法。 定义接口 接口通…

php实现的分页

php实现的分页

PHP 实现分页的方法 基本分页逻辑 分页的核心在于计算总页数、当前页码以及数据偏移量。假设每页显示 10 条数据: $current_page = isset($_GET['page']) ? (…

php 实现队列

php 实现队列

PHP 实现队列的方法 PHP 可以通过多种方式实现队列功能,以下是几种常见的实现方法: 使用数组实现队列 PHP 数组可以通过 array_push 和 array_shift 函数模拟队列的先进…

php实现伪静态

php实现伪静态

PHP 实现伪静态的方法 伪静态(URL Rewrite)是一种将动态URL转换为看似静态URL的技术,提升SEO友好性和用户体验。以下是几种常见的实现方式: 使用 Apache 的 mod_rew…