Nodejs Nestjs限流插件@nestjs/throttler的使用

Nodejs Nestjs限流插件@nestjs/throttler的使用
[@nestjs](/user/nestjs)/throttler 是一个用于 NestJS 的限流插件,它可以帮助你限制特定路由或整个应用的请求速率。下面是如何使用 [@nestjs](/user/nestjs)/throttler 的步骤。

安装

首先,你需要安装 [@nestjs](/user/nestjs)/throttler 和其依赖:

npm install [@nestjs](/user/nestjs)/throttler

配置

在你的 NestJS 应用中配置 ThrottlerModule。通常情况下,你可以在 app.module.ts 中进行配置:

import { ThrottlerModule } from '[@nestjs](/user/nestjs)/throttler';

@Module({
  imports: [
    ThrottlerModule.forRoot({
      ttl: 60, // 请求有效时间(秒)
      limit: 10, // 在指定时间内允许的最大请求数
    }),
  ],
})
export class AppModule {}

全局限流

如果你想对所有路由应用限流规则,你可以在全局范围内使用 ThrottlerGuard

import { ThrottlerGuard } from '[@nestjs](/user/nestjs)/throttler';
import { Module, UseGuards } from '[@nestjs](/user/nestjs)/common';

@Module({
  providers: [
    {
      provide: APP_GUARD,
      useClass: ThrottlerGuard,
    },
  ],
})
export class ThrottlerAuthGuardModule {}

局部限流

你也可以为特定的控制器或路由设置限流规则。例如,你可以为一个控制器添加限流规则:

import { Controller, Get } from '[@nestjs](/user/nestjs)/common';
import { Throttle } from '[@nestjs](/user/nestjs)/throttler';

@Controller('users')
@Throttle(5, 60) // 每分钟最多5个请求
export class UsersController {
  @Get()
  findAll() {
    return 'This action returns all users';
  }
}

你还可以为特定的路由方法单独设置限流规则:

@Controller('users')
export class UsersController {
  @Get()
  @Throttle(5, 60) // 每分钟最多5个请求
  findAll() {
    return 'This action returns all users';
  }

  @Post()
  @Throttle(2, 60) // 每分钟最多2个请求
  create() {
    return 'This action adds a new user';
  }
}

自定义限流存储器

默认情况下,[@nestjs](/user/nestjs)/throttler 使用内存作为存储器。如果你需要持久化存储,可以自定义存储器。例如,使用 Redis 作为存储器:

import { ThrottlerStorageRedis } from '[@nestjs](/user/nestjs)/throttler/dist/storage/throttler-storage-redis';

ThrottlerModule.forRoot({
  storage: new ThrottlerStorageRedis({ client: redisClient }),
}),

确保你已经正确配置了 Redis 连接。

以上就是如何在 NestJS 中使用 [@nestjs](/user/nestjs)/throttler 插件的基本步骤。你可以根据实际需求调整限流规则和存储策略。


3 回复

当然,了解@nestjs/throttler插件能让您的应用更健壮!想象一下,您的应用就像是一场音乐会,而这个插件就是保安,确保每位访客(请求)都能有序入场,不会因为人太多而挤爆现场。

首先,安装插件:

npm install --save [@nestjs](/user/nestjs)/throttler

然后,在您的AppModule中配置它:

import { ThrottlerModule } from '[@nestjs](/user/nestjs)/throttler';

@Module({
  imports: [
    ThrottlerModule.forRoot({
      ttl: 60, // 在60秒内允许的请求数
      limit: 10, // 每个IP最多10次请求
    }),
  ],
})
export class AppModule {}

如果需要对特定路由或控制器进行限流,可以这样设置:

import { ThrottlerGuard } from '[@nestjs](/user/nestjs)/throttler';
import { Module, UseGuards } from '[@nestjs](/user/nestjs)/common';

@Module({
  providers: [
    {
      provide: APP_GUARD,
      useClass: ThrottlerGuard,
    },
  ],
})
export class ApplicationModule {}

或者直接在控制器或方法上添加装饰器:

@Get()
@Throttle(5, 60) // 每分钟最多5次请求
getHello(): string {
  return this.appService.getHello();
}

现在,您的应用就像一位有经验的DJ,知道如何管理好每一场派对,让每个人都有一个愉快的体验!


@nestjs/throttler 是一个用于 NestJS 应用程序的限流插件,它可以有效地限制客户端对应用接口的访问速率。下面是如何在 NestJS 项目中使用 @nestjs/throttler 的步骤:

安装依赖

首先,你需要安装 @nestjs/throttlerexpress-rate-limit(作为适配器):

npm install @nestjs/throttler express-rate-limit

配置 ThrottlerGuard

在你的主模块(通常是 app.module.ts)中配置 ThrottlerModule:

import { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { ThrottlerModule, ThrottlerGuard } from '@nestjs/throttler';

@Module({
  imports: [
    ThrottlerModule.forRoot({
      ttl: 60, // 在指定时间内的请求数量
      limit: 10, // 允许的最大请求数量
    }),
  ],
  providers: [
    {
      provide: APP_GUARD,
      useClass: ThrottlerGuard,
    },
  ],
})
export class AppModule {}

使用 ThrottlerGuard

你可以在需要限流保护的控制器或方法上使用 @Throttle() 装饰器来指定限流规则。

控制器级限流

import { Controller, Get, Post, Body, HttpCode } from '@nestjs/common';
import { Throttle } from '@nestjs/throttler';

@Controller('example')
export class ExampleController {

  @Get()
  @Throttle(5, 60) // 每60秒最多5次请求
  findAll() {
    return 'This action returns all examples';
  }

  @Post()
  create(@Body() createExampleDto: any) {
    return 'This action adds a new example';
  }
}

方法级限流

你也可以为特定的方法设置不同的限流策略:

import { Controller, Get, Post, Body, HttpCode } from '@nestjs/common';
import { Throttle } from '@nestjs/throttler';

@Controller('example')
export class ExampleController {

  @Get()
  @Throttle(5, 60) // 每60秒最多5次请求
  findAll() {
    return 'This action returns all examples';
  }

  @Post()
  @Throttle(2, 30) // 每30秒最多2次请求
  create(@Body() createExampleDto: any) {
    return 'This action adds a new example';
  }
}

注意事项

  • ttl 参数表示令牌桶的时间范围(以秒为单位)。
  • limit 参数表示在该时间段内允许的最大请求数。
  • 如果请求超过了限流规则,NestJS 默认会返回 HTTP 状态码 429 (Too Many Requests)。

通过这种方式,你可以灵活地控制你的 API 接口的访问频率,防止滥用和 DoS 攻击。

@nestjs/throttler 是一个用于 NestJS 应用程序的限流插件。首先安装插件:

npm install @nestjs/throttler throttler

然后在你的模块文件中引入并配置 ThrottlerGuard:

import { ThrottlerModule, ThrottlerGuard } from '@nestjs/throttler';
import { Module, UseGuards } from '@nestjs/common';

@Module({
  imports: [
    ThrottlerModule.forRoot({
      ttl: 60, // 时间窗口(秒)
      limit: 10, // 请求限制
    }),
  ],
  providers: [],
})
export class AppModule {}

最后,在需要限流的控制器或方法上使用 ThrottlerGuard:

import { Controller, Get, UseGuards } from '@nestjs/common';
import { ThrottlerGuard } from '@nestjs/throttler';

@Controller('example')
@UseGuards(ThrottlerGuard)
export class ExampleController {
  @Get()
  getHello(): string {
    return 'Hello World!';
  }
}

这样就实现了对 ExampleControllergetHello 方法进行限流。

回到顶部