我有一个集群 nodejs 应用程序(1 个 Master 和 4 个 Workers)的设置。
主人实例化工人并创建一堆他们可以抓取的任务。
每个工作人员都像这样启动一个数据库连接:
import Database from './db';
//Worker
class Worker {
constructor(process) {
this.process = process;
this.id = process.pid;
this.db = new Database();
console.log('[Worker][', this.id, '][Init] Ready');
this.process.on('message', this.onMessage.bind(this));
}
onMessage(msg) {
this.task = msg.task;
new Task(this.task, this.db);
}
}
我的数据库类如下所示:
import mongoose from 'mongoose';
import bluebird from 'bluebird';
import config from '../server/config/config.json';
import MyModel from '../server/model/mymodel';
class Database {
constructor() {
this.db = config.db;
this.connect();
}
connect() {
mongoose.Promise = bluebird;
mongoose
.connect(this.db.uri, {
user: this.db.user,
pass: this.db.pass,
auth: {
authdb: this.db.authdb
},
promiseLibrary: bluebird,
autoIndex: true,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 500,
poolSize: 10,
bufferMaxEntries: 0
})
.then(() => {
console.log('connected');
})
.catch(err => {
console.log(err);
);
});
}
async save(prices) {
if (prices) {
try {
let bulkUpdate = MyModel.collection.initializeUnorderedBulkOp();
//bulkUpdate is UNDEFINED !!!
prices.forEach(price => {
bulkUpdate
.find({ price: price })
.upsert()
.updateOne(price);
});
await bulkUpdate.execute();
} catch (err) {
console.log(err);
}
}
else {
console.log('[Worker] No prices provided to save.');
}
}
}
还有我的任务课:
class Task {
constructor(url, db) {
this.url = url;
this.db = db;
}
onDataReceived(prices) {
if (prices) {
try {
this.db.save(prices);
}
catch (err) {
console.log('Could not save data.');
console.log(err);
}
}
else {
console.log('No data received');
return;
}
}
}
当我执行代码时,bulkUpdate
变量在之后未定义,initializeUnorderedBulkOp()
因此我无法.find()
对其执行 a 。
经过一番研究,似乎月鹅可能还没有连接。问题是我在执行console.log('connected');
之前有控制台日志initializeUnorderedBulkOp()
,所以我认为它是连接的。
我的问题是,问题在哪里?使用集群的事实是否会混淆猫鼬或我初始化它的方式?
谢谢