领先的免费Web技术教程,涵盖HTML到ASP.NET

网站首页 > 知识剖析 正文

每日一题 |10W QPS高并发限流方案设计(含真实代码)

nixiaole 2025-04-26 20:15:17 知识剖析 1 ℃

面试场景还原

面试官:“如果系统要承载10W QPS的高并发流量,你会如何设计限流方案?”
你:“(稳住,我要从限流算法到分布式架构全盘分析)…”

一、为什么需要限流?

核心矛盾:系统资源(CPU/内存/数据库连接)有限,突发流量可能导致服务雪崩。
目标:在保障系统稳定的前提下,尽可能处理更多请求。
关键指标:QPS(每秒查询量)、并发线程数、响应时间。


二、单机限流 vs 分布式限流

类型

适用场景

优缺点

单机限流

单节点服务、网关层

实现简单,但集群流量不均

分布式限流

微服务集群、云原生架构

精准控制全局流量,但实现复杂


三、四大经典限流算法及代码实战

1固定窗口计数器

原理图

规则

  • 每1秒重置计数器
  • 阈值:1000次/秒

PHP实现

class FixedWindowLimiter {
    private $redis;
    private $key;
    private $limit;
    private $windowSize;

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

    public function allow() {
        $now = time();
        $current = $this->redis->get($this->key);
        
        if ($current && $current >= $this->limit) {
            return false;
        }
        
        $this->redis->multi();
        $this->redis->incr($this->key);
        $this->redis->expire($this->key, $this->windowSize);
        $this->redis->exec();
        return true;
    }
}

// 使用示例
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$limiter = new FixedWindowLimiter($redis, 'api_limit', 1000);
if (!$limiter->allow()) {
    http_response_code(429);
    exit('Too many requests');
}

优缺点

  • 实现简单,内存占用低
  • 窗口切换时可能突发2倍流量

2滑动窗口计数器

原理图


规则

  • 将1秒拆分为10个子窗口(每0.1秒一个)
  • 动态统计最近10个子窗口的总和

PHP实现(Redis)

class SlidingWindowLimiter {
    private $redis;
    private $keyPrefix;
    private $sublimit;
    private $subWindows;

    public function __construct($redis, $keyPrefix, $sublimit, $subWindows = 10) {
        $this->redis = $redis;
        $this->keyPrefix = $keyPrefix;
        $this->sublimit = $sublimit;
        $this->subWindows = $subWindows;
    }

    public function allow($userId) {
        $now = microtime(true);
        $windowSize = 1; // 1秒窗口
        $subWindowSize = $windowSize / $this->subWindows;
        
        // 生成子窗口Key
        $currentSubWindow = floor($now / $subWindowSize);
        $keys = [];
        for ($i = 0; $i < $this->subWindows; $i++) {
            $keys[] = "{$this->keyPrefix}:{$userId}:" . ($currentSubWindow - $i);
        }
        
        // Redis事务统计
        $this->redis->multi();
        foreach ($keys as $key) {
            $this->redis->incr($key);
            $this->redis->expire($key, $windowSize);
        }
        $results = $this->redis->exec();
        
        $total = array_sum(array_slice($results, 0, $this->subWindows));
        return $total <= $this->sublimit;
    }
}

优缺点

  • 解决固定窗口临界问题
  • 内存消耗较高(需存储多个子窗口)

3令牌桶算法

原理图

规则

  • 令牌生成速率:1000个/秒
  • 桶最大容量:2000个(应对突发流量)

PHP实现(Redis原子操作)

class TokenBucketLimiter {
    private $redis;
    private $rate;
    private $capacity;
    private $key;

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

    public function allow() {
        $now = microtime(true);
        $data = $this->redis->hMGet($this->key, ['tokens', 'last_time']);
        
        $tokens = $data['tokens'] ?? $this->capacity;
        $lastTime = $data['last_time'] ?? $now;
        
        // 计算新令牌
        $timePassed = $now - $lastTime;
        $newTokens = $timePassed * $this->rate;
        $tokens = min($tokens + $newTokens, $this->capacity);
        
        if ($tokens < 1) {
            return false;
        }
        
        // 消费令牌
        $this->redis->hSet($this->key, 'tokens', $tokens - 1);
        $this->redis->hSet($this->key, 'last_time', $now);
        return true;
    }
}

优缺点

  • 允许突发流量,平滑限流
  • 需要维护令牌状态,实现较复杂

4漏桶算法

原理图


规则

  • 流出速率:1000次/秒
  • 桶容量:500次(排队等待)

PHP实现(队列模拟)

class LeakyBucketLimiter {
    private $queue;
    private $leakRate;
    private $capacity;
    private $lastLeakTime;

    public function __construct($leakRate, $capacity) {
        $this->queue = new SplQueue();
        $this->leakRate = $leakRate; // 每秒处理数
        $this->capacity = $capacity;
        $this->lastLeakTime = microtime(true);
    }

    public function allow() {
        $this->leak();
        if ($this->queue->count() >= $this->capacity) {
            return false;
        }
        $this->queue->enqueue(microtime(true));
        return true;
    }

    private function leak() {
        $now = microtime(true);
        $delta = $now - $this->lastLeakTime;
        $leakCount = $delta * $this->leakRate;
        
        while ($leakCount > 0 && !$this->queue->isEmpty()) {
            $this->queue->dequeue();
            $leakCount--;
        }
        $this->lastLeakTime = $now;
    }
}

优缺点

  • 严格限制流量速率
  • 无法应对突发流量

四、算法对比与选型建议

算法

适用场景

优势

缺陷

固定窗口计数器

简单低频场景

实现简单

临界突发流量

滑动窗口计数器

API网关

平滑限流

内存消耗高

令牌桶

突发流量容忍型系统

允许突发

实现复杂度高

漏桶

恒定速率处理场景(如支付)

严格控速

无弹性


五、高并发算法优化技巧

  1. Redis Pipeline:批量操作减少网络开销
  2. Lua脚本:保证原子性(如计数器自增+过期时间设置)
  3. 本地缓存:结合本地Guava Cache减少Redis访问
  4. 预热机制:系统启动时缓慢增加限流阈值


六、高并发场景下的优化策略

  1. 分层限流:Nginx网关层 + 服务层 + 细粒度方法级限流。
  2. 动态调整阈值:结合监控系统(Prometheus)实时调节。
  3. 降级熔断:Hystrix/Sentinel触发限流后自动降级。
  4. 集群扩缩容:K8s自动扩缩容 + 弹性计算资源。

七、大厂真实方案参考

  • Google:Guava RateLimiter单机令牌桶。
  • 阿里:Sentinel集群流控 + Warm Up预热机制。
  • Spring Cloud Gateway:基于Redis的分布式限流过滤器。

面试加分点

“我会根据业务场景选择算法,比如API网关用令牌桶保证突发流量,支付系统用漏桶控制恒定速率。分布式场景下,优先使用Redis+Lua保证原子性,并配合Sentinel做熔断降级…”

最近发表
标签列表