2017-04-17 50 views
0

我想使用的Node.js應用如何解決內存泄漏因.MAP功能

從我的MSSQL數據庫9萬條記錄導出到一個MySQL數據庫我遇到了內存問題的node.js ()藍色鳥Promise.map

下面的Myfucntion()調用doThis()函數,它從我的Mssql數據庫獲取一組記錄,然後將記錄插入MySql數據庫。

Myfucntion(){ 
Promise.map(ids, id => doThis(id).then(results => console.log(results)), { concurrency: 5}); 
} 

const doThis = async (id) => { 
    try{ 
     const results = await sql.query`select results where id = ${id}`; 
     if((results && results.recordset) && results.recordset.length > 0) { 
      results.recordset.map(asset => insertResultslAsset(convertResultAsset(asset))); 
     } 
    } 
    catch(err){ 
     console.log(err) 
    } 
}; 

convertResultAsset(asset)函數在插入之前創建一個4屬性對象。

我懷疑發生存儲器泄漏,因爲經轉換的資產被遞增地存儲在存儲器中與所述.MAP迭代

我能夠通過上運行--max歲空間尺寸= 20000到緩解了問題該程序。

在執行doThis()函數的插入之後,我不需要存儲轉換後的資產。

有沒有辦法從.map函數釋放這些對象?

+0

我的50美分:處理9M記錄時,您的代碼應該針對性能進行優化,而不是對友好性進行優化。我認爲你最好使用經典的for循環,並且......獲得一堆id然後查詢它們有什麼用?還有另一種方式嗎?這些9毫升的查詢是你想要執行的嗎?此代碼是轉換的運行一次腳本嗎?還是會定期運行? – user5328504

+0

'insertResultslAsset'或'convertResultAsset'實現可能會泄漏。 – Will

回答

1

在一塊代碼中有太多的asyncpromises。此外,藍鳥有內部錯誤處理程序掛鉤,所以沒有必要使用try-catch塊(可能,這一塊可能會降低性能,請參閱這篇文章:optimization-killers

這是第一個簡化版本:

const debug = require('debug')('my-app-name') 

Myfucntion(){ 
    return Promise.map(
     ids, 
     id => doThis(id), 
     { concurrency: 5} 
    ) 

} 

function doThis(id) { 
    const results = sql.query('select results where id = ${id}'); 
    if (
     results && 
     results.recordset && 
     results.recordset.length > 0 
    ) { 
     return results 
      .recordset 
      .map(asset => insertResultslAsset(convertResultAsset(asset))) 
      .then(res => debug(res)) 
      .catch(err => debug('error', err); 
    } 
    return null 
} 

我已經刪除了console.log,bcz我不確定它的異步/同步性質,debug模塊可能在大多數情況下效果更好(但要看到它的輸出,您應該使用環境標誌運行程序,如下所示:DEBUG=* nodejs app.js

而且我不知道100%這個問題就解決了,因爲兩個未知的功能仍然存在:

  • insertResultslAsset
  • convertResultAsset

可能是這些功能包括封鎖,以及不必要的鎖變量?

+1

這非常簡單! – user5328504

+0

@ user5328504,對不起,我沒有發送代碼。可能'Ctrl + Enter'被按到早期))) – maxkoryukov

+0

這有幫助。我完全按照你所說的去做。我的記憶現在非常穩定。仍然無法弄清究竟是什麼罪魁禍首。 – user1526912