13

I just wanted to know, at the beginning of my NodeJS process, if Redis is started or not (so users session will be stored or not).

Here is what I have for the moment :

var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var redis = require("redis");
var client = redis.createClient(global.redis.host, global.redis.port);

// Check if redis is running
var redisIsReady = false;
client.on('error', function(err) {
    redisIsReady = false;
    console.log('redis is not running');
    console.log(err);
});
client.on('ready', function() {
    redisIsReady = true;
    console.log('redis is running');
});

// Here I use express-session, but I want to set a store only if redis is ready
    sessOptions = {
        [...]
    }
    // Store setting
    if (redisIsReady) {
        sessOptions.store = new RedisStore({
            host: global.redis.host,
            port: global.redis.port
        });
    } else {
        console.log("redis is not running - sessions won't be written to disk");
    }
// app.use(session(sessOptions))

Here is what it's output in both cases (when Redis is running or not) :

redis is not running - sessions won't be written to disk
redis is not running
Error: Redis connection to 6379:localhost failed - connect ENOENT

So I have 2 questions :

  1. How can I do to check if redis is running before setting my SessionStore (is there anyway to check synchronously if redis is running) ?

  2. Why does it giving me an error even when redis is running ?

THANKS!


Note : I'm using default host/port (localhost, 6379) and the RedisStore works as expected.

Note 2 : I'm using Windows... but don't be affraid, it should have the same behavior!

Update : Question #2 answered by vmx => Thanks!

Update 2 : Question #1 answered by Nathan => Thanks!

4

5 回答 5

15

我过去是如何做到这一点的,是在通过设置 redis 连接之间

var client = redis.createClient(global.redis.port, global.redis.host);

并且实际上启动我的应用程序,无论是快速应用程序还是自定义应用程序,我只需执行一个非常简单的查询,例如:

client.get(this.testKey, function(err,res) {
  if(err) 
    throw err;

  if(res === expectedValue)
    return startApp();
});

基本上只需将启动应用程序的代码放在对 redis 查询的回调中,然后您将根据结果知道 redis 是否正在运行。

于 2014-06-15T17:29:35.217 回答
7

2 个问题,首先创建 Redis 客户端的调用顺序错误,先createClient()获取port,然后是host,还有另一个可选options参数。

var client = redis.createClient(global.redis.port, global.redis.host);

其次,您仍然无法实现您的目标;

  1. 该事件是异步触发的,在您检查标志ready时它可能尚未收到就绪响应。redisIsReady
  2. 该标志redisIsReady将设置为 true,但现在您的会话初始化代码可能已经执行。

在初始化会话对象之前,您必须等待,然后才能从中获取errorready事件。redis

希望这可以帮助。

于 2014-06-15T17:23:37.757 回答
3

例子:

 if (client.connected) {
    client.set(key, JSON.stringify(value));
  } else {
    console.log('redis not connected!');
  }
于 2021-03-10T11:19:07.763 回答
1

您还可以使用 node redis api 进行检查:

if (client.connected){
  ...
} else {
  ...
}
于 2020-08-04T13:20:35.653 回答
-3

您可以简单地使用sudo service redis-server status来检查本地机器上 redis 的当前运行状态。希望能帮助到你。

于 2018-07-01T16:18:03.750 回答