【问题标题】:Access Redis inside Route Handler in Express 2.x在 Express 2.x 的 Route Handler 中访问 Redis
【发布时间】:2022-01-20 03:21:19
【问题描述】:

我使用 CLI 创建了一个 Express 2.x 应用程序。所以我有一个路由目录和一个 index.js。 现在,在 app.js 中,我已经连接到 Redis,并且可以正常工作。

我在这里从 app.js 调用 routes/index.js 文件中的函数:

app.post('/signup', routes.myroute);

myroute 函数包含从 Redis 获取密钥的代码。

现在,我收到 redis 未定义的错误。 如何将 redis 对象从 app.js 传递到 routes/index.js?

【问题讨论】:

    标签: node.js routes express redis


    【解决方案1】:

    最简单的解决方案

    您的 app.js 中可能有一个包含 redis 库的 require() 函数。只需将该行添加到 index.js 文件的顶部即可。

    如果您使用的是 node_redis 模块,只需包含以下内容:

    var redis = require("redis"),
    client = redis.createClient();
    


    替代方法

    如果您希望重用现有连接,请尝试将 client 变量传递给 index.js 中的函数:

    app.js

    app.post('/signup', routes.myroute(client));
    

    index.js

    exports.myroute = function(client) {
        // client can be used here
    }
    

    【讨论】:

    • 嘿,谢谢...它可以工作...我只是想知道,它会再次连接到 Redis 服务器,还是使用现有连接来避免过多的开销?
    • 还有没有其他方法可以直接将redis对象传递给路由?
    • 嗯,节点模块一旦加载就会被缓存,所以那里没有开销......但实际的连接可能是一个新的。使用可重用连接的替代解决方案更新答案
    • 此外,我非常怀疑与 redis 的另一个连接会导致任何性能问题。 Redis 非常小而且很高效。
    【解决方案2】:

    您使用的是 Express,因此使用的是 Connect,因此请使用 Connect 中间件。特别是会话中间件。 Connect 的会话中间件具有存储的概念(存储会话内容的地方)。该存储可以在内存中(默认)或数据库中。所以,使用 redis 存储 (connect-redis)。

    var express = require('express'),
        RedisStore = require('connect-redis')(express),
    util = require('util');
    
    var redisSessionStoreOptions = {
        host: config.redis.host, //where is redis
        port: config.redis.port, //what port is it on
        ttl: config.redis.ttl, //time-to-live (in seconds) for the session entry
        db: config.redis.db //what redis database are we using
    }
    
    var redisStore = new RedisStore(redisSessionStoreOptions);
    redisStore.client.on('error', function(msg){
        util.log('*** Redis connection failure.');
        util.log(msg);
        return;
    });
    redisStore.client.on('connect', function() {
        util.log('Connected to Redis');
    });
    
    app = express();
    
    app.use(express.cookieParser());  
    app.use(express.session({ 
            store: redisStore, 
            cookie: {   path: '/', 
                        httpOnly: true, //helps protect agains cross site scripting attacks - ie cookie is not available to javascript
                        maxAge: null }, 
            secret: 'magic sauce',  //
            key: 'sessionid' //The name/key for the session cookie
        }));
    

    现在,Connect 会话魔术将会话详细信息放在传递到每个路由的“req”对象上。 这样,您不需要到处传递 redis 客户端。让 req 对象为您工作,因为无论如何您都可以在每个路由处理程序中免费获得它。

    确保您执行以下操作: npm install connect-redis

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-29
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 2021-07-07
      • 2017-07-17
      • 1970-01-01
      相关资源
      最近更新 更多