限速(流)
原创2026/3/5大约 1 分钟
保护应用免受暴力攻击的常用技术是 rate-limiting。 首先,你需要安装 @nestjs/throttler 包。
npm i --save @nestjs/throttler安装完成后,可以使用 forRoot 或 forRootAsync 方法将 ThrottlerModule 配置为任何其他 Nest 包
使用
import { Module } from '@nestjs/common'
import { UserModule } from './modules/user/user.module'
import { ThrottlerModule, ThrottlerGuard } from '@nestjs/throttler'
import { APP_GUARD } from '@nestjs/core'
@Module({
imports: [
ThrottlerModule.forRoot([
{
ttl: 1000 * 60,
limit: 60,
},
]),
UserModule,
],
providers: [
{
provide: APP_GUARD,
useClass: ThrottlerGuard,
},
],
})
export class AppModule {}上面的内容将为 ttl(生存时间)和 limit(ttl 内的最大请求数)这里我设置的是每分钟60次请求,设置全局选项,用于保护应用的路由。
导入模块后,你可以选择绑定 ThrottlerGuard 的方式。 guards 部分中提到的任何类型的绑定都可以。 例如,如果你想全局绑定守卫,你可以通过将此提供程序添加到任何模块来实现
还有 @Throttle() 装饰器,可用于覆盖全局模块中设置的 limit 和 ttl,以提供更严格或更宽松的安全选项。 这个装饰器也可以用在类或函数上。 这个装饰器的顺序很重要,因为参数的顺序是 limit, ttl。 你必须像这样配置它:
import { Controller, Post } from '@nestjs/common'
import { UserService } from './user.service'
import { Throttle } from '@nestjs/throttler'
@Controller('user')
export class UserController {
constructor(private readonly userService: UserService) {}
@Throttle({ default: { limit: 3, ttl: 1000 * 60 } })
@Post('/one')
findOne() {
return {
msg: 1,
}
}
}至此,本章节的学习就到此结束了,如有疑惑,可对接技术客服进行相关咨询。