我正在运行大量的后台工作,并在一项特定工作中继续遇到竞争状态。
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。
我想做的是对一组ProfilePicture文档设置一个悲观锁定,该文档满足profile_id == self.profile_id或至少在ProfilePicture集合上。
我无法找到关于Mongoid或Mongo的本机锁定的任何内容,所以我查看了一些宝石。
我添加了afeld / mongoid-locker,但这仅适用于单个模型实例。我尝试添加trakio / mongo-lock和servio / mongo-locking,但无法弄清楚如何使用mongo-lock(' my_key'引用?)和mongo-locking给了我一个来源Active_Support 3.0.4的错误
如何对属于特定Profile文档的ProfilePicture文档集进行悲观锁定?
答案 0 :(得分:0)
对于那些关心的人,我能够通过从profile_picture模型中删除selected属性,然后将selected_pic_id属性添加到配置文件模型来解决此问题。这允许我以原子方式更新配置文件模型,而不是尝试更新profile_picture文档的集合。