我正在尝试将可尾光标与流一起使用。我们正在使用 Mongoose ,它可以工作,但是当我使用此代码启动服务器时:
const listStream = ListsSub.find()
.tailable({
await_data: true,
numberOfRetries: -1,
})
.stream();
我的 CPU 过热。
代码处于事件状态时的事件监视器
注释 .stream()
使服务器再次运行良好。
代码被注释时的事件监视器
没有它我真的不知道该怎么办。 我的代码有什么问题吗?有人遇到过同样的问题吗?
编辑:
- Mongoose :4.11.3
- mongodb:3.4.6
- Node :8.1.2
- 服务器和mongodb在同一台机器上
最佳答案
这里实际上有几件事要做。首先值得注意的是使用 .cursor()
方法而不是 .stream()
正如在其他使用时发出的弃用警告中实际指出的那样:
DeprecationWarning: Mongoose: Query.prototype.stream() is deprecated in mongoose >= 4.5.0, use Query.prototype.cursor() instead
第二个值得注意的是 .cursor()
中指定的文档中,这现在直接从底层驱动程序返回“包装流”接口(interface)。所以推荐使用现代的.addCursorFlag()
选项而不是 .tailable()
来自 Mongoose 的方法 Query
.
一旦这两个措施都到位,我看到 mongod
和 node
进程的空闲 CPU 下降到 0%
更新间隔之间。
最好用下面的 list 模拟。
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
关于node.js - 当我使用带有 .stream() 的 mongo tailable 光标时,我的 CPU 过热,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45503546/