Home Articles

RedisStore忽略主机和端口字段

Asked
Viewed 737 times
2

我正在使用 expressconnect-redis 让服务器使用Redis进行会话 .

import Session from 'express-session';
const session = Session({
  resave: true,
  saveUninitialized: true,
  key: '...', 
  secret: '...',
  store: initializeRedis(Session);
});

redis初始化程序如下所示:

import { createClient as createRedisClient } from 'redis';
import connectRedis from 'connect-redis';

export default function initializeRedis(Session) {
  const redisClient = createRedisClient();
  const RedisStore = connectRedis(Session);
  return new RedisStore({
    host: 'redis',
    port: 6378,
  });
}

根据之前的option parameters,服务器应连接 redis 而不是默认 127.0.0.1 通过端口 6378 而不是默认 6379

但是,无论这些值等于什么,我总是得到相同的输出:

错误:Redis连接到127.0.0.1:6379失败 - 连接ECONNREFUSED 127.0.0.1:6379

在配置过程中有什么我错过的吗?

1 Answer

  • 1

    TL; DR

    Redis客户端缺少 hostport 参数 . RedisStore 内没有客户 .

    const redisClient = createRedisClient({
      host: 'redis',
      port: 6379
    });
    
    return new RedisStore({
      client: redisClient,
    });
    

    帖子末尾的完整复制粘贴代码,以防对其他人有用 .

    完整版

    有几种方法可以解决上面的代码 .

    1. The const redisClient = createRedisClient() was assigned nowhere ,但它仍在进行连接工作 . 因此,服务器崩溃,因为它无法连接,但它不是 RedisStore 错误 .

    当我发布问题时,我没有注意到那条线路在那里,我认为它因为商店而崩溃了 .

    事实上,没有那条线它起作用,因为RedisStore has a default client implementation .

    或使用主机,端口或套接字参数为您创建 .

    return new RedisStore({
        host: 'redis',
        port: 6379,
      });
    

    2. The redis client was missing the host and port custom values (默认值为 '127.0.0.1'6379

    import { createClient as createRedisClient } from 'redis';
      const redisClient = createRedisClient({
        host: 'redis',
        port: 6379
      });
    

    如果我们使用特定的客户端实现,我们将它传递给 RedisStore 也是有意义的:

    const RedisStore = connectRedis(Session);
      return new RedisStore({
        client: redisClient,
      });
    

    完整的外卖代码

    server.js

    import Session from 'express-session';
    import initializeRedis from './redis';
    
    // Initialize session.
    const session = Session({
      resave: true,
      saveUninitialized: true,
      key: 'SID',
      secret: 'Luke Skywalker',
      store: initializeRedis(Session)
    });
    app.use(session);
    

    redis.js

    import { createClient as createRedisClient } from 'redis';
    import connectRedis from 'connect-redis';
    
    export default function initializeRedis(Session) {
      const redisClient = createRedisClient({
        host: 'redis', // or '127.0.0.1'.
        port: 6379,
      });
      const RedisStore = connectRedis(Session);
      return new RedisStore({ client: redisClient });
    }
    

Related