首页 > 解决方案 > 使用猫鼬模型的 Node.js 函数中的内存泄漏

问题描述

我有一个 1000 行的 Node.js 脚本,用作移动游戏的后端服务器。我注意到它一直在消耗内存,直到它崩溃并由forever自动重新启动。按照手册、教程和以前的答案,我得出的结论是,这个函数发生了巨大的内存泄漏。我知道是这种情况,因为我增加了这个特定函数的负载并且内存泄漏速度加速到 20kBps,我确信这确实是内存泄漏而不仅仅是自然内存使用,因为它在内存使用率达到 100% 后每隔几个小时就会崩溃在我的服务器上。

var {Room} = require('./models/room');
//...
//...
//...
app.post('/updateRooms',(req,res)=>{
    let currentTime = new Date().getTime();
    Room.find({
        ip: req.body.ip,
        port: req.body.port
    }).then((result)=>{
        if(result.length==0){
            let room = new Room({
                ip: req.body.ip,
                port: req.body.port,
                location: req.body.location,
                difficulty: req.body.difficulty,
                playerAmount: req.body.playerAmount,
                lastUpdate: currentTime
            });
            room.save();
        } else {
            Room.findOneAndUpdate({
                ip: req.body.ip,
                port: req.body.port
            },{
                $set :{
                    difficulty: req.body.difficulty,
                    playerAmount: req.body.playerAmount,
                    lastUpdate: currentTime
                }
            }).then((r)=>{
                console.log(r); 
            });
        }
    result.length = 0;
    }).catch((e)=>{ console.log(e); });
});

此函数由 Axios 的外部脚本调用,该脚本发送有关游戏房间容量的更新。有几个上述脚本的实例(游戏的几个房间)会不断发送有关他们托管的玩家数量的更新。

“{Room}”模型是一个普通的猫鼬模型:

var mongoose = require('mongoose');

var Room = mongoose.model('Room', { 
  ip: {
    type: String,
    required: true,
    minlength: 1,
    trim: true
  },
  port: {
    type: String,
    required: true,
    minlength: 1,
  },
  location: {
    type: String,
    required: true,
    minlength: 1,
  },
  difficulty: {
    type: String,
    required: true,
    minlength: 1,
  },
  playerAmount: {
    type: Number,
    default: 0
  },
  lastUpdate: {
    type: Number,
    default: 0
  }
});

module.exports = {Room};

我尝试在使用后清空发送的数组(result.length=0),但内存泄漏不断发生。知道是什么原因造成的吗?

标签: javascriptnode.jsmongodbmongoosememory-leaks

解决方案


推荐阅读