node.js - 查询数据库时 express.js 中的内存泄漏
问题描述
我目前正在努力解决 express.js 中的内存泄漏问题。通过注释掉其余的代码,我设法缩小到以下范围:
const db = require("../models")
class AuthorizationService {
constructor(app) {
this.db = db(app)
}
async retrieveRealmByDeviceId(req) {
await this.db.Device.find({
where: {
id: "1"
}
})
}
}
module.exports = AuthorizationService
给定的代码与原始代码不同,但它仍然会导致泄漏。我也是 express.js 的新手,并且在代码结构上苦苦挣扎,因为这是一个带有遗留代码的项目。
该../models
文件夹包含一堆使用 Sequelize 定义的模型,例如:
const Sequelize = require("sequelize")
module.exports = (sequelize, DataTypes) => {
const Device = sequelize.define("device", {
id: {
type: Sequelize.STRING,
primaryKey: true,
unique: true
},
userIdentifier: {
type: Sequelize.STRING
}
})
Device.associate = (models) => {
Device.hasMany(models.AuthenticationChallenge, {
as: "ACS",
foreignKey: "deviceId",
sourceKey: "id",
onDelete: "cascade"
})
Device.hasMany(models.DeviceCertificate, {
as: "DCS",
foreignKey: "deviceId",
sourceKey: "id"
})
Device.belongsTo(models.Realm, {
foreignKey: "realmId",
targetKey: "id"
})
Device.belongsToMany(models.Certificate, {
as: "CS",
through: models.DeviceCertificate,
foreignKey: "deviceId",
otherKey: "certificateId",
constraints: false
})
}
return Device
}
我不确定可能需要哪些其他信息,但请务必告诉我。
什么可能导致这种泄漏?我怎样才能检测到它?
编辑:
我们刚刚通过介绍:
await this.db.sequelize.close()
根据文档,关闭:“关闭此 sequelize 实例使用的所有连接,并释放所有引用,以便实例可以被垃圾收集。”
然而,这个选择似乎是为了保持数据库连接而设计的,可能是出于性能原因。如果我们以这种方式管理连接,我们是否应该预料到某种瓶颈或其他数据库性能问题?还是我们应该在请求期间保持连接?简而言之,在 express.js 中管理连接的正确方法是什么?
解决方案
推荐阅读
- git - 受影响的文件 Jenkins 提供未更改的文件
- r - 尝试安装 ROI.plugin.gurobi 时出现问题
- ios - 如何在我的 Xcode 项目中添加附加功能
- laravel - 如何在父母和孩子上应用 Laravel Eloquent where() 条件(hasMany() 关系)
- cookies - 网站如何获得用户的许可来设置其 cookie?
- node.js - 为什么我不能获取记录在 dynamoosejs 中有一个包含主键值的数组字段?
- javascript - 我们如何在 ASP mvc 中通过 ajax 下载 XML 文件?
- editor - Monaca 编辑器语法高亮是可以的,但是编辑器没有显示任何错误
- c++ - 在 Ubuntu 18.04 的 VIsual Studio 代码中为 C++ 设置 OpenCV
- javascript - 使用 javascript 客户端,如何显示“虚拟文件夹”(= 具有相对路径的 html、img、js 的连贯集合)?