3
我有一個使用Mongoid的find_or_create_by方法的web應用程序。在Mongoid中find_or_create_by線程安全嗎?
poll = Poll.find_or_create_by(fields)
在我們投入生產之前,我試圖運行這些故障場景,而且我發現多個用戶可能嘗試使用此方法訪問此資源。它是否有可能創建同一個對象的多個實例?我能做些什麼來防止這種情況發生?
我有一個使用Mongoid的find_or_create_by方法的web應用程序。在Mongoid中find_or_create_by線程安全嗎?
poll = Poll.find_or_create_by(fields)
在我們投入生產之前,我試圖運行這些故障場景,而且我發現多個用戶可能嘗試使用此方法訪問此資源。它是否有可能創建同一個對象的多個實例?我能做些什麼來防止這種情況發生?
聲明:我是Mongoid和Rails的新手,所以我可能完全錯誤。
看着modifiable.rb和many.rb它似乎沒有鎖定任何資源。
它看起來對我來說,它只是做了「其中()第一次。」查詢,然後如果不返回任何它進行「創造」查詢:
def find_or(method, attrs = {}, &block)
where(attrs).first || send(method, attrs, &block)
end
對於find_or_create_by,「發送」稱之爲「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
結論:對我來說,這似乎是一個方便的方法,不要指望它是「線程安全的」。我希望有更多關於這種方法的文檔。