【问题标题】:I am trying to connect to an online redis server from heroku but my connection is getting refused我正在尝试从 heroku 连接到在线 redis 服务器,但我的连接被拒绝
【发布时间】:2020-01-29 04:14:24
【问题描述】:

我正在使用 Node.js (ioredis) 的 Redis 包,我有一个托管在 ScaleGrid 上的 redis 集群,我试图从 heroku 连接,但我不断收到错误 [ioredis] Unhandled error event: Error: connect ECONNREFUSED 127.0.0.1:6379 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14) Redis Error: { ReplyError: NOAUTH Authentication required.。这是我的代码

//This is what my redis uri provided by ScaleGrid uri looks like, this is not exact string though
REDIS_URI=SG-Stack-12345.servers.mongodirector.com:6379

import session from 'express-session';
import Redis from 'ioredis';
import connectRedis from 'connect-redis';

const redisClient = process.env.REDIS_URI;

const redis = new Redis(redisClient);
const redisStore = connectRedis(session);

redis.on('error', (err) => {
  console.log('Redis Error:', err);
});

app.use(session({
  secret: process.env.SESSION_SECRET,
  name: '_redisSession',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: false },
  store: new redisStore({ client: redis, ttl: 86400 }),
}));

请问我该如何解决这个问题?还有为什么我仍然得到这个Error: connect ECONNREFUSED 127.0.0.1:6379

P.S. Redis 在我的本地主机上完美运行

【问题讨论】:

    标签: node.js heroku redis ioredis


    【解决方案1】:

    我意识到我需要的只是在 redis 客户端连接(client.auth(password) 后立即发送验证密码。 由于一些奇怪的错误,我不得不为我的 redis 主机解决 redislabs enterprise 并且还不得不从 ioredis 包更改为 redis 包。这是下面的代码

    redis.js

    import { createClient } from 'redis';
    
    const {
      PASSWORD: password,
      REDIS_HOST: host, // On localhost, set to 'localhost' or '127.0.0.1'
      REDIS_PORT: port, // On localhost,  set to 6379
    } = process.env;
    
    // connect to Redis host with port and host set as environment variables
    const client = createClient(port, host, { no_ready_check: true });
    
    // If password is in environment variable, send password to the host for authentication
    if (password) {
      client.auth(password, (err) => {
        if (err) throw err;
      });
    }
    
    client.on('connect', () => console.log('connected to Redis'));
    
    client.on('error', (err) => {
      console.log('Redis Error:', err);
    });
    
    export default client;
    

    这是可选的,它只显示连接的redis客户端在索引文件中是如何使用的。

    index.js

    import session from 'express-session';
    import connectRedis from 'connect-redis';
    import client from './redis'
    
    const redisStore = connectRedis(session);
    
    app.use(session({
      secret: 'IwontTell',
      name: '_stackOverflow',
      resave: false,
      saveUninitialized: true,
      cookie: { secure: false },
      store: new redisStore({ client, ttl: 86400 }),
    }));
    

    这在本地主机和在线上都可以完美运行。希望这可以帮助某人

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-09
      • 1970-01-01
      • 2014-10-18
      • 1970-01-01
      • 1970-01-01
      • 2021-07-03
      • 2019-05-06
      • 1970-01-01
      相关资源
      最近更新 更多