繁体   English   中英

nodejs 应用程序中的内存泄漏,关于全局变量的建议

[英]memory leak in nodejs app, advice on global variables

第一次内存泄漏我需要在 Nodejs/JS 上调试,所以这里有一些新手问题。 我想得到一些关于代码设计的建议……特别是:

我有一个mysql数据库的连接,我把它作为一个全局变量打开,这样我就不必建立连接和拆卸了。 我有频繁的访问请求。 我已经连接到谷歌服务,同样,在全局级别建立一个连接对象,这样我就不必每次都重新连接并延迟用户。 对于上面的 1 和 2,我应该对内存泄漏有任何负面担忧吗? (与在函数范围内调用和拆除它们相比)

片段:

import  mysql from 'mysql';
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'xxxx',
    password: 'xxx',
    database: 'xxx' ,
    charset: 'utf8mb4'
});

 connection.connect((err) => {
    if (err) throw err;
    console.log('Connected!');
});
...
export {connection as default};

这是另一个:

import config from './config.json';
import Discord from 'discord.js';

//discord bot
const bot = new Discord.Client();

// We also need to make sure we're attaching the config to the CLIENT so it's accessible everywhere!
bot.config = config;
bot.commands = new Discord.Collection();
bot.aliases = new  Discord.Collection();
bot.help = new Discord.Collection();

bot.login(config.token);

export default bot;

和谷歌连接

// Imports the Google Cloud client library
import { TranslationServiceClient } from '@google-cloud/translate';

// instantiate an instance of a connection to google translate API
const translationClient = new TranslationServiceClient();

想知道是否有不同/更好的方法来解决这个问题?

IMO 最好像这样初始化连接,因为在您导出连接时,它没有建立,这可能会导致不同的问题。

 const createMsqlConnection = () => { return new Promise((resolve, reject) => { const connection = mysql.createConnection({ host: 'localhost', user: 'xxxx', password: 'xxx', database: 'xxx' , charset: 'utf8mb4' }); connection.connect((err) => { if (err) reject(err); console.log('connected') resolve(connection); }); }) } const start = async () => { const connection = await createMsqlConnection() // use connection here... } start.then()

所以换句话说,与其导出连接,不如导出创建它的 Promise

事实证明我没有内存泄漏。 在执行了大量跟踪之后,我确定 GC 确实在收集并且我没有任何增长的块。

在谷歌搜索其他问题之后,我了解到的是,我只是同时获得了更多的流量,这超出了我在峰值线程并发命中时可用的内存。

我增加了 VM 的内存,但最初并没有帮助,这让我明白这是一个设置问题。 我需要增加可用节点内存的大小,这解决了问题。 已经运行了几天没有增长。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM