redis连接+ singleton + node.js

时间:2018-05-16 06:29:43

标签: javascript node.js redis

我正在使用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

2 个答案:

答案 0 :(得分:0)

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位于相同级别的目录中)

编辑:修正了一些错误

答案 1 :(得分:0)

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);
});

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