【发布时间】:2017-08-18 11:24:19
【问题描述】:
过去 1 周我都面临这个问题,对此我感到很困惑。 保持简短和简单地解释问题。
我们有一个内存模型,它存储预算等值。现在,当调用 API 时,它有与之关联的支出。
然后我们检查内存模型并将花费添加到现有花费中,然后检查预算,如果超出,我们不再接受该模型的任何点击。对于每个调用,我们还更新数据库,但这是一个异步操作。
一个简短的例子
api.get('/clk/:spent/:id', function(req, res) {
checkbudget(spent, id);
}
checkbudget(spent, id){
var obj = in memory model[id]
obj.spent+= spent;
obj.spent > obj.budjet // if greater.
obj.status = 11 // 11 is the stopped status
update db and rebuild model.
}
这曾经可以正常工作,但现在并发请求我们得到虚假支出,支出增加超过预算,并且在一段时间后停止。我们用 j 米模拟了呼叫并发现了这一点。
据我们所知,节点是异步的,所以当状态更新到 11 时,许多线程已经更新了活动的花费。
如何为 Node.js 提供信号量逻辑,以便可变预算与模型同步
更新
db.addSpend(campaignId, spent, function(err, data) {
campaign.spent += spent;
var totalSpent = (+camp.spent) + (+camp.cpb);
if (totalSpent > camp.budget) {
logger.info('Stopping it..');
camp.status = 11; // in-memory stop
var History = [];
History.push(some data);
db.stopCamp(campId, function(err, data) {
if (err) {
logger.error('Error while stopping );
}
model.campMAP = buildCatMap(model);
model.campKeyMap = buildKeyMap(model);
db.campEventHistory(cpcHistory, false, function(err) {
if (err) {
logger.error(Error);
}
})
});
}
});
代码的 GIST 可以请任何人帮忙
【问题讨论】:
-
We then check the in memory model and add the spent to the existing spend这会更新内存模型吗? -
update db and rebuild model.所以,你只重建模型一次 status == 11?重建是同步的吗?还是一旦数据库更新就完成了,毫无疑问是异步的 - 确实一些真实的代码会更容易回答 -
是的,这更新了模型@JaromandaX
-
是的,只有当它是 11 时,我们才更新数据库,但我们在更新数据库之前更新内存模型,是的,数据库调用是 async 。抱歉,我无法分享生产代码
-
并发,多线程还是多进程?您知道这不会解决您的问题,反而会使问题更加复杂,对吧?
标签: javascript node.js concurrency