Загрузка…
Загрузка…
Node.js · middle · сложность 5
Стратегии ограничения ставок:
Подходы к реализации:
// Using express-rate-limit middleware
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: 'Too many requests from this IP',
standardHeaders: true,
legacyHeaders: false,
});
app.use('/api/', limiter);
// Custom Redis-based rate limiter
const redis = require('redis');
const client = redis.createClient();
const rateLimitMiddleware = (limit, window) => {
return async (req, res, next) => {
const key = `rate_limit:${req.ip}`;
const current = await client.incr(key);
if (current === 1) {
await client.expire(key, window);
}
if (current > limit) {
return res.status(429).json({ error: 'Rate limit exceeded' });
}
next();
};
};Варианты хранения:
Расширенные возможности:
Лучшие практики:
Кэширование в памяти:
// Simple memory cache with TTL
class MemoryCache {
constructor() {
this.cache = new Map();
this.timers = new Map();
}
set(key, value, ttl = 60000) {
// Clear existing timer
if (this.timers.has(key)) {
clearTimeout(this.timers.get(key));
}
this.cache.set(key, value);
// Set expiration timer
const timer = setTimeout(() => {
this.cache.delete(key);
this.timers.delete(key);
}, ttl);
this.timers.set(key, timer);
}
get(key) {
return this.cache.get(key);
}
}Кэширование Redis:
const redis = require('redis');
const client = redis.createClient();
// Cache with Redis
async function getCachedData(key) {
const cached = await client.get(key);
if (cached) {
return JSON.parse(cached);
}
const data = await fetchFromDatabase(key);
await client.setex(key, 300, JSON.stringify(data)); // 5 min TTL
return data;
}Шаблоны кэширования:
Стратегии аннулирования кэша:
Ключевой вывод для интервью: как реализовать ограничение скорости в API Express.js?