Skip to content

接口限流

保护 API 免受恶意请求或突发流量冲击。

实现方式

使用 Redis + 中间件实现滑动窗口限流:

typescript
// src/core/middlewares/rate-limit.middleware.ts
@Injectable()
export class RateLimitMiddleware implements NestMiddleware {
  async use(req: Request, res: Response, next: NextFunction) {
    const key = `rate:${req.ip}:${req.path}`;
    const count = await this.redis.incr(key);
    
    if (count === 1) await this.redis.expire(key, 60);
    if (count > 100) { // 每分钟 100 次
      throw new TooManyRequestsException();
    }
    next();
  }
}

默认规则

规则限制说明
全局限流100 req/min/IP所有接口通用
登录接口5 req/min/IP防暴力破解
文件上传20 req/min/IP防资源滥用

自定义限制

在控制器上使用 @Throttle() 装饰器覆盖默认值:

typescript
@Throttle({ limit: 5, ttl: 60000 }) // 每分钟最多 5 次
@Post('login')
login(@Body() dto: LoginDto) { ... }

下一步:

基于 MIT 许可发布 · 由 ❤️ 和 ☕ 驱动 · 支持作者