Appearance
限流
保护应用程序免受暴力攻击的常用技术是速率限制 , 首先需要安装扩展包。
pnpm add @nestjs/throttler
全局定义
然后在 app.module.ts 中定义模块
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler'
@Module({
imports: [
ThrottlerModule.forRoot({
//每60秒
ttl: 60,
//限制接口访问10次
limit: 10,
}),
],
//定义全局守卫,这样可以在其他模块中使用限流
providers: [
{
provide: APP_GUARD,
useClass: ThrottlerGuard,
},
],
})
export class AppModule {}
控制器
可以对控制器方法进行单独限流设置,来覆盖全局限流的定义
import { Throttle } from '@nestjs/throttler'
@Controller('code')
export class CodeController extends BaseController {
@Post('send')
//限制每120秒请求1次
@Throttle(1, 120)
async send(@Body() dto: CodeDto) {
...
}
}