美文网首页
node.js redis 同步取值 bluebird asyn

node.js redis 同步取值 bluebird asyn

作者: 去年的牛肉 | 来源:发表于2020-05-20 09:57 被阅读0次
    1. 安装redis库
    npm install --save redis
    
    1. ../../.../config.js
    module.exports = {
        // ...
        redis: {
            host: "172.16.0.224",
            port: 6379,
            options: {
                password: "myredispassword",
                timeout: 3000
            }
        },
        spam: {
            limit: 3,
            seconds: 60,
        },
        // ...
    }
    
    1. 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 请求频繁限制
    

    相关文章

      网友评论

          本文标题:node.js redis 同步取值 bluebird asyn

          本文链接:https://www.haomeiwen.com/subject/luhgohtx.html