3

我正在开发我的项目,该项目基于 socket.io room。我将socket与nodejs一起使用并在mongoDB中管理房间数据。

这是我的代码,只有两个玩家可以加入一个房间,然后在我将 IsGameOn 标志 false 设置为 true 之后。
当我将请求一一发送到服务器时,此代码工作正常。
当一次有多个请求时会出现问题。问题是超过 2 个玩家加入房间(房间玩家的数据存储在 aPlayers 数组中)。

我也上传了数据库的图像。因此,您可以看到数据库中实际发生的情况。

const joinRoom = async (sData, callback) => {

if(sData.iPlayerId && sData.eRoomCount)
{
    try {

        let body = _.pick(sData, ['eRoomCount', 'iPlayerId']);

        console.log(body);

        await roomsModel.aggregate([
            {
                $match: {
                    eRoomCount: body.eRoomCount,
                    IsGameOn: { $eq: false }
                }
            },
            { $unwind: "$aPlayers" },
            {
                $group: {
                    _id: "$_id",
                    eRoomCount: { $first: "$eRoomCount" },
                    aPlayers: { $push: "$aPlayers" },
                    size: { $sum: 1 }
                }
            },
            {
                $match: {
                    size: { '$lt': body.eRoomCount }
                }
            },
            { $sort: { size: -1 } }
        ]).exec((error, data) => {
            if (data.length < 1) {

                let params = {
                    eRoomCount: body.eRoomCount,
                    aPlayers: [{
                        iPlayerId: body.iPlayerId
                    }]
                }
                let newRoom = new roomsModel(params);
                console.log(JSON.stringify(newRoom));
                newRoom.save().then((room) => {
                    console.log("succ", room);
                    callback(null,room);
                }).catch((e) => {
                    callback(e,null);
                });
            } else {
                roomsModel.findOne({ _id: data[0]._id }, (error, room) => {

                    if (error) {
                        callback(error,null);
                    }

                    if (!room) {
                        console.log("No room found");
                        callback("No room found",null);
                    }

                    room.aPlayers.push({ iPlayerId: body.iPlayerId });
                    if (room.aPlayers.length === room.eRoomCount) {
                        room.IsGameOn = true;
                    }

                    room.save().then((room) => {
                        callback(null,room);
                    }).catch((e) => {
                        callback(e,null);
                    });

                })
            }
        });

    } catch (e) {
        console.log(`Error :: ${e}`);
        let err = `Error :: ${e}`;
        callback(e,null);
    }
    }
}

当请求一一来时,就会发生这种情况。 当请求一一来时,就会发生这种情况。

当一次有许多请求时会发生这种情况。 在此处输入图像描述

4

2 回答 2

2

正确的方法是使用 mongoose'sfindOneAndUpdate而不是findOne. 操作findOneAndUpdate是原子的。如果你做正确的查询,你可以让你的代码线程安全。

// This makes sure, that only rooms with one or no player gets selected.
query = {
    // Like before
    _id: data[0]._id,
    // This is a bit inelegant and can be improved (but would work fast)
    $or: {
        { aPlayers: { $size: 0 } },
        { aPlayers: { $size: 1 } }
    }
}

// $addToSet only adds a value to a set if it not present.
// This prevents a user playing vs. him/herself
update = { $addToSet: { aPlayers: { iPlayerId: body.iPlayerId } } }

// This returns the updated document, not the old one
options = { new: true }

// Execute the query
// You can pass in a callback function
db.rooms.findOneAndUpdate(query, update, options, callback)
于 2018-06-15T13:13:38.270 回答
1

对于这个问题,您可以使用信号量模块,在您的情况下,节点服务器在单线程环境中访问并发请求,但操作系统执行多任务工作。信号量模块将帮助您摆脱这个地狱。

  • npm i 信号量(安装模块)
  • const sem = require('信号量')(1); (要求并指定并发请求限制为 1 )
  • sem.take(函数()); (将您的功能包装在其中)
  • sem.leave(); (处理完成后调用它,然后下一个请求将访问该函数)

    const joinRoom = (sData, callback) => {
    
      sem.take(function () {
        if (sData.iPlayerId && sData.eRoomCount) {
    
          try {
    
            let body = _.pick(sData, ['eRoomCount', 'iPlayerId']);
            roomsModel.aggregate([
              {
                $match: {
                  eRoomCount: body.eRoomCount,
                  IsGameOn: { $eq: false }
                }
              },
              { $unwind: "$aPlayers" },
              {
                $group: {
                  _id: "$_id",
                  eRoomCount: { $first: "$eRoomCount" },
                  aPlayers: { $push: "$aPlayers" },
                  size: { $sum: 1 }
                }
              },
              {
                $match: {
                      size: { '$lt': body.eRoomCount }
                    }
                  },
                  { $sort: { size: -1 } }
                ]).exec((error, data) => {
                  if (data.length < 1) {
    
                    let params = {
                      eRoomCount: body.eRoomCount,
                      aPlayers: [{
                        iPlayerId: body.iPlayerId
                      }]
                    }
                    let newRoom = new roomsModel(params);
                    console.log(JSON.stringify(newRoom));
                    newRoom.save().then((room) => {
                      console.log("succ", room);
                      sem.leave();
                      callback(null, room);
                    }).catch((e) => {
                      sem.leave();
                      callback(e, null);
                    });
                  } else {
                    roomsModel.findOne({ _id: data[0]._id }, (error, room) => {
                      if (error) {
                        sem.leave();
                        callback(error, null);
                      }
                      if (!room) {
                        console.log("No room found");
                        sem.leave();
                        callback("No room found", null);
                      }
                      room.aPlayers.push({ iPlayerId: body.iPlayerId });
                      if (room.aPlayers.length === room.eRoomCount) {
                        room.IsGameOn = true;
                      }
                      room.save().then((room) => {
                        sem.leave();
                        callback(null, room);
                      }).catch((e) => {
                        sem.leave();
                        callback(e, null);
                      });
                    });
                  }
                });
              } catch (e) {
                console.log(`Error :: ${e}`);
                let err = `Error :: ${e}`;
                callback(e, null);
              }
            }
          });
        }
    
于 2018-06-18T07:46:09.293 回答