首页 > 解决方案 > 查询数据库时 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 中管理连接的正确方法是什么?

标签: node.jsexpressmemory-leakssequelize.js

解决方案


推荐阅读