【问题标题】:how to connect to redis db with username and password nodejs node-redis如何使用用户名和密码连接到 redis 数据库
【发布时间】:2023-01-11 17:15:06
【问题描述】:

我如何连接到具有用户名和密码的Redis 数据库? 下面是我尝试使用的代码示例,(我正在使用nodejsnode-redisRedis版本“redis”:“^3.0.0”,)

const client = redis.createClient({
  host: "localhost",
  port: 6379,
  password: "1234",
  username: "username"
});

【问题讨论】:

  • 你得到哪个错误?
  • 我没有收到任何错误,但这是实现它的正确方法吗?很难找到关于此的任何文档

标签: node.js redis


【解决方案1】:

取决于您使用的 Node Redis 版本。由于看起来您正在使用 Node Redis 3.x,因此它看起来像这样:

const client = redis.createClient({
  host: "localhost",
  port: 6379,
  password: "1234",
  user: "username"
});

您还可以使用连接字符串进行连接:

const client = redis.createClient("redis://username:1234@localhost:6379");

Node Redis 的 GitHub 存储库中的 tagged branch 提供了 3.x 的完整文档。

也就是说,我建议使用 Node Redis 4.x,因为它支持 Promises、更新的 Redis 命令和许多常见的 Redis 模块,如 RedisJSON 和 RediSearch。

使用 4.x 连接:

const client = redis.createClient({
  socket: {
    host: "localhost",
    port: 6379
  }
  password: "1234",
  username: "username"
});

或者:

const client = redis.createClient({ url: "redis://username:1234@localhost:6379" });

有关使用 Node Redis 4.x 进行连接的详细信息,请参阅 Node Redis 主分支上的 READMEClient Configuration Guide

【讨论】:

  • 如果我使用的是 redis 3.x.x,我需要 client.quit() 吗?这是必要的吗?如果我不退出会导致任何错误吗?
  • 当我想关闭连接时,我通常使用client.quit(),因为它让 Redis 知道要处理连接在本地关闭它。当我调用 client.close() 时遇到了问题,Redis 不知道连接已断开,然后我就用完了连接。也就是说,对于 Node.js 应用程序,我通常只保持一个连接打开,将其用于所有内容,并在进程结束时调用 client.quit()
  • 我对所有 Redis 客户端都这样做,无论语言或版本如何。
【解决方案2】:

连接 Nodejs 项目Redis 版本 ^4.x:

const redisClient = redis.createClient({
  socket: {
    host: "localhost",
    port: 6379
  }
  password: "1234",
  username: "username"
});
redisClient.on("error", (error) => console.error(`Error : ${error}`));
redisClient.connect();
console.log('Redis Connected !!');

如果您不提供套接字、密码或用户名,则默认情况下它将连接127.0.0.1:6379

对于默认连接使用 Beloved 提及代码

const redisClient = redis.createClient();
redisClient.on("error", (error) => console.error(`Error : ${error}`));
redisClient.connect();
console.log('Redis Connected !!');

【讨论】:

    猜你喜欢
    • 2018-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2016-12-19
    • 2015-06-29
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多