接口限流
保护 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) { ... }下一步:
