nodejs基于koa框架的IP访问限流

插件

koa-ratelimit

使用‍

const Koa = require(‘koa’);
const ratelimit = require(‘koa-ratelimit’);
const Redis = require(‘ioredis’);

const app = new Koa();

app.use(ratelimit({

‘driver’: ‘redis’,

‘db’: new Redis({

‘max_clients’: 10,

‘min_clients’: 1,

‘port’: 6379,

‘host’: ‘127.0.0.1’,

‘password’: ‘1234567’,

}),

‘duration’: 60000, // 时间 毫秒

‘errorMessage’: ‘Sometimes You Just Have to Slow Down.’,

‘id’: ctx => ctx.ip, // IP作为唯一key

‘headers’: {

‘remaining’: ‘Rate-Limit-Remaining’,

‘reset’: ‘Rate-Limit-Reset’,

‘total’: ‘Rate-Limit-Total’,

},

‘max’: 5, // 60秒内最大访问次数5

‘disableHeader’: false,

‘whitelist’: ctx => { // 白名单

// console.log(‘whitelist===========>’, ctx);

// some logic that returns a boolean

‘blacklist’: ctx => { // 黑名单 高频访问ip 可以写在这里

// console.log(‘blacklist===========>’, ctx);

}));

app.use(async ctx => {

ctx.body = ‘Stuff!’;

});

app.listen(3000);

console.log(‘listening on port 3000’);

const RateLimit = require("koa2-ratelimit").RateLimit;
const Stores = require("koa2-ratelimit").Stores;
//Detailed Redis Configuration Reference: https://github.com/redis/node-redis/blob/master/docs/client-configuration.md
RateLimit.defaultOptions({
  message: {
    code: 429,
    msg: "请求超过并发限制",
  },
  store: new Stores.Redis({
    socket: {
      host: process.env.REDIS_HOST,
      port: process.env.REDIS_PORT,
    },
    password: "",
    database: 1,
  }),
});

const getPdfRateLimit = RateLimit.middleware({
  max: process.env.PDF_RATE_LIMIT,
});
const getScreenshotRateLimit = RateLimit.middleware({
  max: process.env.SCREENSHOT_RATE_LIMIT,
});

访问 http://127.0.0.1:3000

作者:Jeebiz  创建时间:2023-02-27 18:24
最后编辑:Jeebiz  更新时间:2024-02-28 14:53