【问题标题】:redis connection + singleton + node.jsredis 连接 + 单例 + node.js
【发布时间】:2018-10-26 02:12:46
【问题描述】:

我正在使用 redis 在我的项目中存储会话。

app.js

var client  = redis.createClient();

client.on('error', function (err) {
  console.log('could not establish a connection with redis. ' + err);
});
client.on('connect', function (err) {
  console.log('connected to redis successfully');
});

在我的 routes.js 文件中,我必须从 redis 获取所有信息,所以我使用以下内容:

var client = redis.createClient();

client.on('error', function(err){
  console.log('Something went wrong ', err)
});

但每次它连接到redis。如何在我的app.js 中连接一次 redis 并在任何地方使用它。请提出想法。提前致谢。

编辑

app.js

module.exports.client = client;

routes.js

var client = require("../app.js").client;
client.hgetall();

但我收到error

TypeError: Cannot read property 'hgetall' of undefined

【问题讨论】:

  • app.js导出client ..然后将client 导入routes.js
  • @Ritwick Dey 谢谢,你能提供一些例子吗
  • 对不起。我虽然它是一个客户端应用程序。
  • 在这种情况下你必须管理会话
  • @Ritwick Dey 请看我编辑的帖子

标签: javascript node.js redis


【解决方案1】:

app.js

var client  = redis.createClient();

client.on('error', function (err) {
  console.log('could not establish a connection with redis. ' + err);
});
client.on('connect', function (err) {
  console.log('connected to redis successfully');
});

module.exports = { client }

routes.js

var { client } = require('./app');

client.on('error', function(err){
  console.log('Something went wrong ', err)
});

(假设app.jsroutes.js在同一级目录)

编辑:修正了一些错字

【讨论】:

    【解决方案2】:

    app.js

        const redis = require('redis'),
    redisClient = redis.createClient(6379, '127.0.0.1');
    const http = require('http');
    
    const REDIS_USER_DATA_INDEX = 2;
    
    redisClient.select(REDIS_USER_DATA_INDEX);
    
    module.exports.client = redisClient;
    

    routes.js

        const app = require('./app');
    
    app.client.on('connect', function () {
        console.log('redis connected');
        console.log(`connected ${app.client.connected}`);
    }).on('error', function (error) {
        console.log(error);
    });
    

    我希望这能解决您的问题。谢谢

    【讨论】:

      猜你喜欢
      • 2014-03-25
      • 1970-01-01
      • 2020-08-23
      • 2014-12-19
      • 1970-01-01
      • 1970-01-01
      • 2014-04-18
      • 2022-01-13
      • 2018-09-03
      相关资源
      最近更新 更多