为什么Redis没有响应?

fquxozlt  于 2023-10-15  发布在  Redis
关注(0)|答案(1)|浏览(132)

我正在尝试在我的节点后端运行Redis。代码运行良好,直到它到达任何Redis命令,在这一点上它只是停止。没有错误消息或任何内容,例如

const client = redis.createClient()
client.connect().then(() => redisTest())

const redisTest = async () => {
    console.log("running redis test...")
    try {
        client.set("test","val", function(err) {
            if (err) {
               // Something went wrong
               console.error("error");
            } else {
                client.get("test", function(err, value) {
                     if (err) {
                         console.error("error");
                     } else {
                         console.log("Worked: " + value)
                     }
                })
            }
        })
    } catch (error) {
        console.log("Redis error", error)
    }
}

client.on('error', err => console.log('Redis Client Error', err));

控制台会记录“正在运行redis test...”,然后就停止了(至少我会看到一条错误消息)。Redis CLI运行良好,我能够获取和设置值,并且我已经验证了端口号。我也试过

async client.connect()

(async () => {
    await client.connect()
})

这两个都抛出错误。
有什么建议可以解决这个问题吗?

rjee0c15

rjee0c151#

这将返回瓦尔

const client = redis.createClient();

const connectRedis = () => {
  return new Promise((resolve, reject) => {
    client.connect()
    client.on('connect', () => {
      console.log('Connected to Redis server...');
      resolve();
    });
    client.on('error', (err) => {
      console.error('Error connecting to Redis:', err);
      reject(err);
    });
  });
};

const redisTest = async () => {
  try {
    console.log("running redis test...");
    await client.set("test", "val");
    const value = await client.get("test");
    console.log("Worked: " + value);
  } catch (error) {
    console.log("Redis error", error);
  } finally {
    client.quit(); // Close the Redis client after the test is complete.
  }
};

// Usage: Connect to Redis first and then execute the test
connectRedis()
  .then(redisTest)
  .catch((err) => {
    console.error("Error in Redis test:", err);
    client.quit(); // Close the Redis client if there is an error during connection or test.
  });

相关问题