Skip to content
On this page

koa2-ratelimit

简介

koa2-ratelimit 是一个用于限制请求速率的中间件,它可以帮助你控制 API 的访问频率,防止 API 被滥用,保护服务器资源。支持多种存储方式和灵活的配置选项。

安装

bash
npm install koa2-ratelimit

基本使用

javascript
const Koa = require('koa');
const Router = require('@koa/router');
const { RateLimit } = require('koa2-ratelimit');

const app = new Koa();
const router = new Router();

// 全局限制
app.use(RateLimit.middleware({
  interval: { min: 15 }, // 15 分钟
  max: 100 // 最大请求次数
}));

// 特定路由限制
const loginRateLimit = RateLimit.middleware({
  interval: { min: 5 }, // 5 分钟
  max: 5, // 最大尝试次数
  message: '尝试次数过多,请稍后再试'
});

router.post('/login', loginRateLimit, async (ctx) => {
  // 登录逻辑
});

app.use(router.routes());
app.listen(3000);

高级特性

自定义存储

javascript
const RedisStore = require('koa2-ratelimit').RedisStore;

const limiter = RateLimit.middleware({
  store: new RedisStore({
    host: 'localhost',
    port: 6379,
    db: 0
  }),
  interval: { min: 15 },
  max: 100
});

动态配置

javascript
const dynamicLimiter = RateLimit.middleware({
  interval: { min: 15 },
  max: (ctx) => {
    // 根据用户类型设置不同的限制
    return ctx.state.user.isPremium ? 1000 : 100;
  },
  keyGenerator: (ctx) => {
    // 使用用户 ID 作为键
    return ctx.state.user.id;
  }
});

分组限制

javascript
const apiLimiter = RateLimit.middleware({
  interval: { min: 60 },
  max: 1000,
  keyPrefix: 'api_rate_limit'
});

const uploadLimiter = RateLimit.middleware({
  interval: { hour: 1 },
  max: 50,
  keyPrefix: 'upload_rate_limit'
});

router.use('/api', apiLimiter);
router.use('/upload', uploadLimiter);

错误处理

javascript
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    if (err.name === 'RateLimitError') {
      ctx.status = 429;
      ctx.body = {
        error: '请求过于频繁',
        retryAfter: err.resetTime
      };
      return;
    }
    throw err;
  }
});

注意事项

  1. 根据实际需求合理设置限制频率和时间间隔
  2. 在分布式系统中建议使用 Redis 存储
  3. 为不同类型的请求设置不同的限制策略
  4. 添加适当的错误处理和用户提示
  5. 考虑使用动态限制来处理不同用户组的需求

要保持清醒 永远不抱有意外的幻想 凭空的期待最要命