Redis 连接 + 单例模式 + Node.js

5
我正在使用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();

但是我收到了错误

TypeError: Cannot read property 'hgetall' of undefined

app.js 中的 client 导出,然后在 routes.js 中导入该 client - Ritwick Dey
@Ritwick Dey 谢谢,你能否提供一些例子? - Subburaj
在这种情况下,您必须管理会话。 - Ritwick Dey
@Ritwick Dey 请查看我编辑过的帖子。 - Subburaj
抱歉让您感到困惑。请告诉我您需要的是redis.createClient();一个实例/请求,还是一个实例/用户,或者是应用程序全生命周期内的一个实例。 - Ritwick Dey
显示剩余3条评论
2个回答

2
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在同一级目录中)

编辑:修正了几个错别字


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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接