提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
Nginx + NestJS + Redis 三层限流
层次 | 技术 | 限制粒度 | 主要目的 |
---|---|---|---|
Nginx限流层 | Nginx模块 | IP级别限流、防CC攻击 | 请求在到达应用层之前拦截 |
NestJS应用层 | @Throttle装饰器 | 用户级别/API接口级限流 | 精细控制每个接口访问频率 |
Redis分布式层 | ThrottlerStorageRedis | 分布式环境下统一限流 | 保证多实例限流一致 |
✅ 编辑你的 nginx.conf,在对应 server 区块添加:
http {
# 定义限流zone(IP维度)
limit_req_zone $binary_remote_addr zone=seckill_limit:10m rate=100r/s;
server {
listen 80;
location /seckill/ {
# 应用IP限流
limit_req zone=seckill_limit burst=200 nodelay;
proxy_pass http://your-nestjs-service:3000;
proxy_set_header Host $host;
}
}
}
参数 | 含义 |
---|---|
limit_req_zone |
定义限流区域,内存大小10MB,速率100 requests/second |
limit_req |
实际应用到 /seckill/ 路径,瞬间突发允许200个排队,超出直接429 |
✅ 这样做,连入口都打不爆,Nginx直接抗住绝大部分恶意流量。
你的做法已经正确了,只需要调整一下参数,比如:
@Throttle({ short: { limit: 5000, ttl: 1000 } })
如果以后你有NestJS多实例部署(比如k8s、docker swarm集群),内存限流是失效的
,需要基于 Redis来统一限流。
✅ 需要安装:
pnpm add @nestjs/throttler-storage-redis ioredis
✅ 配置到 AppModule
:
import { ThrottlerModule } from '@nestjs/throttler';
import { ThrottlerStorageRedisService } from '@nestjs/throttler-storage-redis';
@Module({
imports: [
ThrottlerModule.forRootAsync({
useFactory: () => ({
ttl: 1, // 1秒
limit: 5000, // 5000次
storage: new ThrottlerStorageRedisService('redis://127.0.0.1:6379'),
}),
}),
],
})
export class AppModule {}
✅ 自动切换到 Redis 来统计流量!
即使有10台NestJS副本,流量统计都是统一的,防止穿透。
[ 外部请求 ]
↓
[ Nginx IP限流: 100r/s 每IP ]
↓
[ NestJS 局部接口限流: 5000r/s每接口 ]
↓
[ Redis 分布式限流: 统一计数 ]
↓
[ 业务逻辑(扣库存、投递Kafka) ]
真正做到:
层级 | 特点 |
---|---|
Nginx | 最先拦截,防大水 |
NestJS | 细粒度接口/用户限频 |
Redis | 集群环境统一限流 |
✅ 这样你的秒杀接口就能抗住几十万QPS的大流量冲击,并且还能细粒度控制