接口限流
youlai-nest 当前未集成限流功能。如有需求,推荐以下方案:
推荐方案
方案一:NestJS Throttler
bash
pnpm add @nestjs/throttler配置:
typescript
// app.module.ts
import { ThrottlerModule } from '@nestjs/throttler';
@Module({
imports: [
ThrottlerModule.forRoot([
{
ttl: 60000, // 时间窗口(毫秒)
limit: 10, // 最大请求数
},
]),
],
})
export class AppModule {}使用:
typescript
import { Throttle } from '@nestjs/throttler';
@Controller('auth')
export class AuthController {
@Throttle({ default: { limit: 3, ttl: 60000 } })
@Post('login')
login() {}
}方案二:Redis + Guard
自定义限流守卫:
typescript
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { RedisService } from '../shared/redis/redis.service';
@Injectable()
export class RateLimitGuard implements CanActivate {
constructor(private redisService: RedisService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const ip = request.ip;
const key = `rate_limit:${ip}`;
const count = await this.redisService.incr(key);
if (count === 1) {
await this.redisService.expire(key, 1); // 1秒过期
}
if (count > 10) {
throw new HttpException('请求过于频繁', 429);
}
return true;
}
}方案三:Nginx 限流
在反向代理层实现限流:
nginx
# 定义限流区域
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
server {
location /api/ {
limit_req zone=api_limit burst=20 nodelay;
proxy_pass http://localhost:8000;
}
}