我已经开发了一个使用node &express和mongoDB(3.2.9) (mongooseJS)托管在mLabs.
当使用沙箱版本时,一切似乎都很好,但是当我升级到使用集群时,我总是发现我覆盖了集合中的最后一个条目。
我不确定这是我的代码还是我需要在mLabs上配置的东西。
连接服务器:
if (cluster.isMaster) {
// Count the CPU's
const cpuCount = require('os').cpus().length;
// Create workers on each CPU
for (let i = 0; i < cpuCount; i += 1) {
cluster.fork();
}
// Listen for dying workers
cluster.on('exit', (worker) => {
// Replace the dead worker
console.log('Worker ${worker.id} died');
cluster.fork();
});
} else {
app.listen(port, () => {
console.log('Worker '+ port +' running');
});
}
保存数据
db.name = productData.name;db。imagePath = productData.imagePath;db。price = Number(productData.price).toFixed(2);db。siteId = productData.siteId;db。
db.save((error, product) => {
if(error) {
utils.handleError(res, error, 'Error message');
} else {
// Add to price history
historyData.saveNewHistory(product._id, productData.price);
if(boardId){
boardData.addProductToBoard(boardId, product.url, product._id, userId, targetPrice, productData.price, res);
}
res.status(201).json({
'status': 201,
'message': 'Added product successfully',
'product' : product
});
}
});
我没有收到任何错误信息如此困惑,为什么它可能覆盖,id是唯一的由MongoDB生成
我忘了说这个APP/API是托管在AWS Beanstalk上的,如果这意味着什么的话。
如果你替换
// Create workers on each CPU
for (let i = 0; i < cpuCount; i += 1) {
cluster.fork();
}
// Create workers on each CPU
//for (let i = 0; i < cpuCount; i += 1) {
cluster.fork();
//}
?
如果是,那么你的应用程序不是线程安全的。升级到集群将使您的应用程序创建更多的worker,如果它们不能很好地协同工作,则可能导致它们覆盖彼此的数据。注释掉for循环会导致流程只生成一个worker。如果不起作用,我也帮不了你。