美文网首页全栈开发
nodejs mongoose redis 千万并发秒杀(一)

nodejs mongoose redis 千万并发秒杀(一)

作者: 去年的牛肉 | 来源:发表于2020-05-20 03:23 被阅读0次

    一 .首先安装redis

    作者用的是oneinstack。
    redis.conf配置文件目录在

    /usr/local/redis/etc/redis.conf
    

    1、修改可以外网访问(一般线上的,不开放,但是我们在测试的时候,可以是外网,也可以是内网,看自己的需求去,)
    更改redis.conf 文件

    bind 127.0.0.1
    protected-mode yes
    

    更改为

    #bind 127.0.0.1 等于这句注释掉
    protected-mode yes
    

    2、设置密码访问。不然损失惨重。

    # requirepass foobared
    requirepass password   
    #password是密码
    

    3、重启redis,即可生效。

    注:记得对防火墙的6379端口可以进行访问
    可用

    #检查可以通再连接
    telnet ip port
    

    二.mongoose-redis 缓存

    接下来插件介绍,天下文章一大抄请允许我引用一段:
    来自:https://www.npmjs.com/package/mongoose-redis#installation

    Installation

    Install via NPM

    npm install mongoose-redis --save
    

    Example

    var mongoose = require('mongoose');
    
    var MongooseCache = require('mongoose-redis');
    

    Config mongoose-redis cache

    var cache = MongooseCache(mongoose, "redis://127.0.0.1:6379");
    
    var docs = await Post.find({ stt: 1 }).sort({ crt: -1 })
    
    .limit(30)
    
    .cache(120) // cache 120 seconds
    
    .select({ tl: 1, lth:1, views:1, img: 1, slug: 1})
    

    You can also pass a custom key into the .cache() method, which you can then use later to clear the cached content.

    app.get('/detail/:id', async (req, res)=> {
    
        var _id = req.params.id;  
    
        var info = await Post.findOne({ slug: _id, stt: 1 })
    
                .cache(120, _id); // custom cache key by id
    
    });
    
    Post.findById("5dbfac4d7d3ff31acb86d870").cache(60).then(result => {
    
            console.log(result);
    
        });
    
    Post.findOne({ _id: '5dbfac4d7d3ff31acb86d870' }).cache(60).then(result => {
    
            console.log(result);
    
        });
    

    代码就这么简单。

    相关文章

      网友评论

        本文标题:nodejs mongoose redis 千万并发秒杀(一)

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