【问题标题】:Redis NodeJs server error,client is closedRedis NodeJs服务器错误,客户端已关闭
【发布时间】:2022-01-08 02:48:51
【问题描述】:

我正在开发一个应用程序,其中聊天必须被缓存和监控,目前它是一个本地应用程序,我已经安装了 redis 和 redis-cli。 我面临的问题是(node:5368) UnhandledPromiseRejectionWarning: Error: The client is closed 下面附上代码sn-p

//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


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回答@Leibale Eidelman :)
    • 这真的很有帮助!谢谢
    【解决方案2】:

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

    import { createClient } from 'redis';
    
    const client = createClient();
    
    await client.connect();
    

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

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

    【讨论】:

    • 你在异步函数之外调用 await
    猜你喜欢
    • 2022-01-08
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 2019-09-01
    • 2015-02-19
    • 1970-01-01
    相关资源
    最近更新 更多