2017-08-04 60 views
4

我試圖用一個tailable光標流我的CPU過熱。我們使用貓鼬,它的工作原理,但當我啓動我的服務器與此代碼:當我使用的是.stream一個蒙戈tailable光標()

const listStream = ListsSub.find() 
    .tailable({ 
    await_data: true, 
    numberOfRetries: -1, 
    }) 
    .stream(); 

我的CPU過熱。

活動監視器當代碼被激活

enter image description here

兼評的.stream()使服務器再次運行偉大。當該代碼是在

活動監視器評論

enter image description here

我真的不知道如何離不開它。 這是否與我的代碼?任何人都遇到同樣的問題?

編輯:

  • 貓鼬:4.11.3
  • 的MongoDB:3.4.6
  • 節點:8.1.2
  • 在同一臺機器上的服務器和MongoDB
+0

這可能是因爲客戶端是「投票」,而不是真正等待事件的有效途徑。貓鼬版本?和MongoDB版本連接請。另外我認爲客戶端和服務器都在同一臺機器上運行? –

+0

對不起,我忘了問'節點'版本。但它實際上似乎更多地指向'mongod',而不是其他任何東西,特別是在OSX上運行。 –

+1

在Ubuntu上運行時,我們遇到同樣的問題。它在Ubuntu上並沒有那麼高,並且它不是過熱,但mongod正在使用〜80%的CPU。 –

回答

6

這裏實際上有幾件事要做。第一值得注意的事情是,而不是使用.stream()如授予棄用警告實際指示的.cursor()方法以其他方式使用時:

DeprecationWarning:貓鼬:Query.prototype.stream()在貓鼬已棄用> = 4.5 0.0,用Query.prototype.cursor()代替

第二值得注意的事情是,作爲.cursor()文檔中指定的,這現在直接從底層驅動程序將返回「包裝流」接口。因此,它是那麼建議使用現代.addCursorFlag()選項,而不是.tailable()方法從貓鼬Query

一旦採取了這兩種措施,我發現mongodnode進程的空閒CPU在更新間隔之間下降到0%

這是最好用下面的上市模擬。

const mongoose = require('mongoose'), 
     Schema = mongoose.Schema; 

mongoose.Promise = global.Promise; 
mongoose.set('debug',true); 

const uri = 'mongodb://localhost/tailing', 
     options = { useMongoClient: true }; 

const subSchema = new Schema({ 
    name: String 
},{ 
    capped: { size: 1024, max: 1000 } 
}); 

const Sub = mongoose.model('Sub', subSchema); 

function log(data) { 
    console.log(JSON.stringify(data, undefined, 2)) 
} 

(async function() { 

    try { 

    const conn = await mongoose.connect(uri,options); 

    //await Sub.remove({}); 

    await Sub.insertMany(Array(50).fill(1).map((e,i) => ({ name: i+1 }))); 

    let stream = Sub.find() 
     .cursor() 
     .addCursorFlag('tailable',true) 
     .addCursorFlag('awaitData',true); 
     /* 
     .tailable({ 
     await_data: true, 
     numberOfRetries: -1 
     }) 
     .cursor(); 
     */ 

    stream.on('data',function(data) { 
     log(data); 
    }); 

    let counter = 50; 


    setInterval(async function() { 
     counter++; 
     await Sub.insertMany({ name: counter }); 
    },10000); 

    } catch(e) { 
    console.log(e); 
    } finally { 
    //mongoose.disconnect(); 
    } 

})(); 

普通老式的大輸出,捕捉爲實際的寫操作:

top - 21:38:29 up 12 days, 1:23, 3 users, load average: 0.06, 0.03, 0.04 
Tasks: 116 total, 2 running, 114 sleeping, 0 stopped, 0 zombie 
%Cpu(s): 0.3 us, 0.3 sy, 0.0 ni, 98.6 id, 0.7 wa, 0.0 hi, 0.0 si, 0.0 st 
KiB Mem : 2045968 total, 207452 free, 813908 used, 1024608 buff/cache 
KiB Swap: 2097148 total, 2097124 free,  24 used. 1028156 avail Mem 

    PID USER  PR NI VIRT RES SHR S %CPU %MEM  TIME+ COMMAND 
1257 mongodb 20 0 1946896 487336 34892 S 0.7 23.8 130:37.67 mongod 
28233 neillunn 20 0 1021460 41920 22996 S 0.3 2.0 0:00.67 node 
30956 neillunn 20 0 101472 4384 3352 S 0.3 0.2 0:20.95 sshd