javascript - 使用猫鼬模型的 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),但内存泄漏不断发生。知道是什么原因造成的吗?
解决方案
推荐阅读
- javascript - 将对象转换为数组的优雅方式
- python - 如何在 Python 的成绩单中找到百分比?
- html - 如何使所有文本行
- 当有填充时,元素具有相同的缩进
- servlets - 如何将值从 ajax 传递到 portlet 页面
- unix - 使用 sed 在特定字符串后添加一行,不能使其适用于涉及 ' ( / 等的字符串
- python - 如何将自定义 python 函数应用于 Tensorflow 中的配对数据?
- python - 如何在 Django REST framework mixin 中引用子类?
- apache-spark - Kubernetes 上的 Zeppelin Spark Master 设置
- android - 如何通过改造在 android 中的 web 中显示 html 响应
- javascript - ReactJS:从.map中导入的数据字符串渲染html