TypeScript中的速率限制:库实现完整指南
速率限制是一种流量控制机制,可防止服务器过载、防御DDoS攻击并确保资源均匀分配。在TypeScript中,得益于严格的类型化和对异步操作的支持,实现速率限制变得尤为便捷。本文将介绍TypeScript中流行的库、策略和代码示例。
为什么需要速率限制?
- 保护API — 限制来自同一客户端(按IP、令牌或ID)的请求数量。
- 防止滥用 — 阻止生成过多负载的机器人或脚本。
- 资源分配 — 确保用户之间公平使用后端资源。
- 遵守外部服务限制 — 控制对第三方API(例如OpenAI或GitHub)的请求。
TypeScript中流行的速率限制库
1. express-rate-limit
最流行的Express.js库。作为中间件运行,开箱即用支持TypeScript。允许按时间设置限制和自定义超限处理程序。
安装:
npm install express-rate-limitnpm install -D @types/express-rate-limit使用示例:
import express from 'express';import rateLimit from 'express-rate-limit';
const app = express();
const limiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15分钟 max: 100, // 每个窗口最多100个请求 message: '请求过多,请稍后再试。', standardHeaders: true, legacyHeaders: false,});
app.use('/api', limiter); // 应用于 /api/*
app.get('/api/data', (req, res) => { res.json({ message: '成功响应' });});
app.listen(3000);特点:
- 内置TypeScript支持(
Request和Response的类型)。 - 灵活配置:可以设置键(按IP、userId、令牌)。
- 状态存储在内存中(默认)或通过Redis。
2. bottleneck
用于客户端速率限制的库 — 当需要控制出站请求(例如,对外部API)时非常理想。基于队列和延迟工作。
安装:
npm install bottleneckTypeScript示例:
import Bottleneck from 'bottleneck';
const limiter = new Bottleneck({ minTime: 200, // 请求之间至少间隔200毫秒 maxConcurrent: 5, // 最多5个并发请求 reservoir: 100, // 周期内总限制 reservoirRefreshAmount: 100, reservoirRefreshInterval: 60 * 1000, // 每60秒});
async function fetchData(id: number): Promise<string> { const response = await fetch(`https://api.example.com/data/${id}`); return response.text();}
// 包装有限制的函数const limitedFetch = limiter.wrap(fetchData);
// 使用async function main() { const results = await Promise.all([ limitedFetch(1), limitedFetch(2), limitedFetch(3), ]); console.log(results);}优点:
- 支持被包装函数的类型。
- 灵活的策略:
minTime、maxConcurrent、reservoir。 - 既可在Node.js中运行,也可在浏览器中运行。
3. p-limit
用于限制并行异步操作的轻量级库。当需要控制同时执行的Promise数量时非常有用。
安装:
npm install p-