如何避免 cursor.observe 上的竞争条件?

编程入门 行业动态 更新时间:2024-10-26 01:22:47
本文介绍了如何避免 cursor.observe 上的竞争条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在我的 Meteor 应用程序中,我在 publish 中做了一个 observe,在某些条件下插入一些新数据.关键是有时我们有重复订阅,竞争条件导致我们重复插入的数据.如果不可能有单一观察者":

In my Meteor application, I made an observe within a publish, that insert some new data in certain conditions. The point is that sometimes we have duplicated subscriptions, and race condition leads us to duplicate inserted data. If it is 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); } }); }

此问题已从cursor.observe 的工作原理以及如何避免多个实例运行?

推荐答案

据汤姆,这是不可能的,现在,确保共享具有相同参数的 subscribe 调用.因此,如果您遇到与我相同的问题,即观察者内部创建的冗余数据,作为解决方法,我建议您:

According to Tom, it is not possible, for now, to ensure that calls to subscribe that have the same arguments are shared. So, if you are having the same problem I had, of redundant data created inside observers, I suggest you, as workaround, to:

  • 创建健壮索引,防止重复创建数据.复合键 很可能就是您所需要的.
  • 在您的观察者中处理重复的关键错误异常,忽略竞争条件.
  • Create robust indexes that prevent repeted data creating. Compound Keys is probable what you need here.
  • Treat duplicate key error exceptions inside your observer ignoring race conditions.
  • 示例:

    Collection.find(selector).observe({ removed: function(document){ try { // Workaround to avoid race conditions > stackoverflow/q/13095647/599991 createNewDocument(); } catch (e) { // XXX string parsing sucks, maybe // jira.mongodb/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(); } });

    更多推荐

    如何避免 cursor.observe 上的竞争条件?

    本文发布于:2023-10-23 19:46:39,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1521834.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:条件   竞争   cursor   observe

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!