Redis NodeJs 服务器错误,客户端已关闭

问题描述 投票:0回答:8

我正在开发一个必须缓存和监控聊天的应用程序,目前它是一个本地应用程序,我已经在其中安装了 redis 和 redis-cli。 我面临的问题是

(node:5368) UnhandledPromiseRejectionWarning: Error: The client is closed
下面附上代码片段

//redis setup
const redis = require('redis');
const client = redis.createClient()//kept blank so that default options are available
  

//runs when client connects
io.on("connect", function (socket) {

  //this is client side socket
  //console.log("a new user connected...");

  socket.on("join", function ({ name, room }, callback) {
    //console.log(name, room);
    const { msg, user } = addUser({ id: socket.id, name, room });
   // console.log(user);
    if (msg) return callback(msg); //accessible in frontend

    //emit to all users
    socket.emit("message", {
      user: "Admin",
      text: `Welcome to the room ${user.name}`,
    });
    //emit to all users except current one
  
    socket.broadcast
      .to(user.room)
      .emit("message", { user: "Admin", text: `${user.name} has joined` });

    socket.join(user.room); //pass the room that user wants to join

    //get all users in the room
    io.to(user.room).emit("roomData", {
      room: user.room,
      users: getUsersInRoom(user.room),
    });

    callback();
  }); //end of join

  //user generated messages
  socket.on("sendMessage",  async(message, callback)=>{
    const user = getUser(socket.id);

    //this is where we can store the messages in redis
    await client.set("messages",message);

    io.to(user.room).emit("message", { user: user.name, text: message });
    console.log(client.get('messages'));
    callback();
  }); //end of sendMessage

  //when user disconnects
  socket.on("disconnect", function () {
    const user = removeUser(socket.id);
    if (user) {
     
      console.log(client)

      io.to(user.room).emit("message", {
        user: "Admin",
        text: `${user.name} has left `,
      });
    }
  }); //end of disconnect

当用户向房间发送消息或调用

socket.on("sendMessage")
时,我遇到上述错误。

我哪里错了?

提前谢谢你。

node.js sockets redis node-redis
8个回答
55
投票

您应该

await client.connect()
在使用客户端之前


36
投票

在node-redis V4中,客户端不会自动连接到服务器,您需要在执行任何命令之前运行.connect(),否则会收到错误ClientClosedError: The client is closed.

import { createClient } from 'redis';

const client = createClient();

await client.connect();

或者您可以使用传统模式来保持向后兼容性

const client = createClient({
    legacyMode: true
});

5
投票

client.connect() 返回一个承诺。你必须使用 .then() 因为你不能在函数外调用 await。

const client = createClient();  
client.connect().then(() => {
  ...
})

4
投票

我遇到了类似的问题,并且能够按如下方式更改连接代码。

const client = redis.createClient({
  legacyMode: true,
  PORT: 5001
})
client.connect().catch(console.error)

2
投票

你不能在函数外调用 await。

const redis = require('redis');
const client = redis.createClient();

client
  .connect()
  .then(async (res) => {
    console.log('connected');
    // Write your own code here

    // Example
    const value = await client.lRange('data', 0, -1);
    console.log(value.length);
    console.log(value);
    client.quit();
  })
  .catch((err) => {
    console.log('err happened' + err);
  });

2
投票

使用

"redis": "3.1.2",
版本。


1
投票

尝试了几种选择。没有工作。

按照mesutpiskin所说的使用redis 3.1.2

这对我有用。

Redis 4.x.x 的连接很复杂

您可以从文档中的片段中尝试redis


0
投票

你不能在函数外调用

await
。这就是我所做的工作。

const redis = require('redis');

const redisClient = redis.createClient()

redisClient.on('connect', () => {
    console.log('Connected to Redis12345');
})

redisClient.on('error', (err) => {
    console.log(err.message);
})

redisClient.on('ready', () => {
    console.log('Redis is ready');
})

redisClient.on('end', () => {
    console.log('Redis connection ended');
})

process.on('SIGINT', () => {
    redisClient.quit();
})

redisClient.connect().then(() => {
    console.log('Connected to Redis');
}).catch((err) => {
    console.log(err.message);
})

在 app.js 中

//just for testing

const redisClient = require('./init_redis')

redisClient.SET('elon', 'musk', redisClient.print)

© www.soinside.com 2019 - 2024. All rights reserved.