【问题标题】:MongoDB: Set collection level pessimistic lockMongoDB:设置集合级别悲观锁
【发布时间】:2015-05-29 20:07:40
【问题描述】:

我正在运行大量后台作业,并且在一项特定作业上一直处于竞争状态。

Rails 4、Mongoid、Sidekiq、Redis

个人资料 has_many ProfilePictures

当这段代码被多个线程调用时

  def set_as_active_picture
    ProfilePicture.where({
      profile_id: self.profile.id,
      selected: true}
    ).update_all('$set' => {selected: false})

    self.set selected: true

    self.profile.set(picture_url: self.image.url)
  end

我遇到了一个竞争条件,其中多个 ProfilePicture 文档已选择设置为 true。

我想做的是对一组满足 profile_id == self.profile_id 或至少在 ProfilePicture 集合上的 ProfilePicture 文档设置悲观锁定。

我找不到任何关于 Mongoid 或 Mongo 的本地锁定的信息,所以我查看了一些 gem。

我添加了 afeld/mongoid-locker 但这仅适用于单个模型实例。我尝试添加 trakio/mongo-lock 和 servio/mongo-locking,但无法弄清楚如何使用 mongo-lock('my_key' 参考什么?)并且 mongo-locking 给了我 Active_Support 3.0 的源错误。 4

如何对属于特定 Profile 文档的 ProfilePicture 文档集进行悲观锁定?

【问题讨论】:

  • 你在一个经典的 mongodb 问题中运行 - 如果可能的话尽快摆脱它 - 好好读一下:developer.olery.com/blog/goodbye-mongodb-hello-postgresql - hn.algolia.com/…
  • 哈哈,你是说这是一个经典的mongodb问题?太好了,这只是我讨厌 mongo 的另一个原因。我很想改用 postgres 之类的东西,但不幸的是这不是我的决定。

标签: ruby-on-rails mongodb concurrency mongoid


【解决方案1】:

对于那些关心的人,我能够通过从 profile_picture 模型中删除 selected 属性并改为将 selected_pic_id 属性添加到 profile 模型来解决这个问题。这让我可以自动更新配置文件模型,而不是尝试更新 profile_picture 文档的集合。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 2010-09-12
    • 1970-01-01
    • 2014-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多