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

Mak*_*and 35 sockets redis node.js node-redis

我正在开发一个必须缓存和监控聊天的应用程序,目前它是一个本地应用程序,我已经安装了 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

Run Code Online (Sandbox Code Playgroud)

当用户向房间发送消息或被socket.on("sendMessage") 呼叫时,我收到上述错误。

我哪里出错了?

先感谢您。

Lei*_*man 78

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


Asa*_*ida 43

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

import { createClient } from 'redis';

const client = createClient();

await client.connect();
Run Code Online (Sandbox Code Playgroud)

或者您可以使用旧模式来保留向后兼容性

const client = createClient({
    legacyMode: true
});
Run Code Online (Sandbox Code Playgroud)

  • 您在异步函数之外调用await (23认同)
  • 您可以包装在异步方法中,例如 (async () => { wait client.connect(); })(); (2认同)

cnm*_*nhh 6

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

const client = createClient();  
client.connect().then(() => {
  ...
})
Run Code Online (Sandbox Code Playgroud)


Tay*_*ell 5

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

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