- 安装redis库
npm install --save redis
- ../../.../config.js
module.exports = {
// ...
redis: {
host: "172.16.0.224",
port: 6379,
options: {
password: "myredispassword",
timeout: 3000
}
},
spam: {
limit: 3,
seconds: 60,
},
// ...
}
- Cache.js
const redis = require("redis");
const config = require("../config/config");
let c = config.redis,
client = redis.createClient(c.port, c.host, c.options);
client.on("error",function(err){
console.log(err);
});
function Cache() {}
let text = async(key)=>{
let doc = await new Promise( (resolve) => {
client.get(key,function(err, res){
return resolve(res);
});
});
return JSON.parse(doc);
};
Cache.set = function(key, value) {
value = JSON.stringify(value);
return client.set(key, value, function(err){
if (err) {
console.error(err);
}
});
};
Cache.get = async(key)=>{
return await text(key);
};
Cache.expire = function(key, time) {
return client.expire(key, time);
};
module.exports = Cache;
Usage:
// begin 请求频繁限制
let ip = Client.getIP(req);
let key = "mail:" + ip;
let ans = await Cache.get(key);
let count = 0;
if (ans) {
logger.debug(ans);
count = parseInt(ans);
}
count++;
Cache.set(key, count);
// 一分钟过期时间
Cache.expire(key, config.spam.seconds);
if (count > config.spam.limit) {
res.json({
code: 16,
data: count,
message: "请求太频繁"
});
return;
}
// end 请求频繁限制
网友评论