比赛条件
在我的 Meteor 应用程序中,我在 publish
中进行了observe
,在某些条件下插入一些新数据。关键是,有时我们有重复的订阅,竞争条件会导致我们重复插入的数据。
如果是not possible to have "singleton observers" :
- 我们如何避免竞争条件和数据库中重复插入的数据?
示例:
Meteor.publish("fortuneUpdate", function () {
var selector = {user: this.userId, seen:false};
DailyFortunes.find(selector).observe({
removed: function(doc, beforeIndex){
if(DailyFortunes.find(selector).count()<1)
createDailyFortune(this.userId);
}
});
}
此问题已从 How cursor.observe works and how to avoid multiple instances running? 移至
最佳答案
According to Tom ,目前无法确保共享具有相同参数的订阅调用。 因此,如果您遇到与我相同的问题,即观察者内部创建的冗余数据,我建议您作为解决方法:
- 创建稳健 indexes防止重复创建数据。 Compound Keys可能就是您所需要的。
- 在观察者内部处理重复的关键错误异常,忽略竞争条件。
示例:
Collection.find(selector).observe({
removed: function(document){
try {
// Workaround to avoid race conditions > https://stackoverflow.com/q/13095647/599991
createNewDocument();
} catch (e) {
// XXX string parsing sucks, maybe
// https://jira.mongodb.org/browse/SERVER-3069 will get fixed one day
if (e.name !== 'MongoError') throw e;
var match = e.err.match(/^E11000 duplicate key error index: ([^ ]+)/);
if (!match) throw e;
//if match, just do nothing.
}
self.flush();
}
});
关于meteor - 如何避免cursor.observe 上的竞争条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13297796/