[英]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.