在Mongoid中find_or_create_by线程安全吗? [英] Is find_or_create_by thread safe in Mongoid?

查看:90
本文介绍了在Mongoid中find_or_create_by线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用Mongoid的find_or_create_by方法的Web应用程序.

I have a web app that uses Mongoid's find_or_create_by method.

poll = Poll.find_or_create_by(fields)

在投入生产之前,我正在尝试遍历所有失败情况,然后我发现多个用户可以尝试使用此方法访问此资源.是否有可能创建同一对象的多个实例?我该怎么做才能防止这种情况?

Before we go into production, I am trying to run through the failure scenarios, and it occurred to me that multiple users could try to access this resource using this method. Is there any likelihood that it could create multiple instances of the same object? What can I do to prevent that?

推荐答案

免责声明:我是Mongoid和Rails的新手,所以我可能完全错了.

Disclaimer: I'm new to Mongoid and Rails so I could be totally wrong.

查看 modifiable.rb many.rb 似乎没有锁定任何资源.

Looking at modifiable.rb and many.rb it doesn't appear to lock on any resource.

在我看来,它只是执行"where().first"查询,然后如果不返回任何内容,则执行创建"查询:

It looks to me like it simply does a "where().first" query and then if that does not return anything it performs a "create" query:

 def find_or(method, attrs = {}, &block)
    where(attrs).first || send(method, attrs, &block)
  end

对于find_or_create_by,发送"将称为"create_document":

For find_or_create_by, "send" would call "create_document":

def create_document(method, attrs = nil, &block)
    klass.__send__(method,
      selector.reduce(attrs || {}) do |hash, (key, value)|
        unless key.to_s =~ /\$/ || value.is_a?(Hash)
          hash[key] = value
        end
        hash
      end, &block)
  end

结论:对我来说,这似乎是一种便捷的方法,不要指望它是线程安全的".我希望有更多关于此方法的文档.

Conclusion: To me this appears to be a convenience method, do not expect it to be "thread-safe". I wish there was more documentation available on this method.

这篇关于在Mongoid中find_or_create_by线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆