如果我从不同的工作人员创建 class 的实例,是否会应用变量缓存?

Does variable caching will be applied if I create an instance of the class from different worker?

我有 2 个工人,两个工人都在调用一个初始化 class 实例的工厂,在初始化方法中我使用了变量缓存,这样两个工人都可以利用变量缓存,同时创建 class.

的实例
class BoxFolderDocumentSynchronizerJob < ActiveJob::Base
  queue_as :default

  def perform(document_store_id, folder_id)
    synchronizer = DocumentSynchronizerFactory.get_synchronizer(document_store, folder_id)
  end
end

class DeleteBoxFolderDocumentJob < ActiveJob::Base
  queue_as :default

  def perform(document_store_id, folder_id=nil)
    synchronizer = DocumentSynchronizerFactory.get_synchronizer(document_store, folder_id)
  end
end

module DocumentSynchronizers
  class Base
    attr_reader :document_store, :facility

    def initialize(document_store, folder_id=nil)
      if document_store
        @folder_id = folder_id
        @document_store  = document_store
        @facility = document_store.facility
        #Fetch all the document store(project) documents from S3/Box service provider
        @service_provider_documents_hash ||= DocumentStoreAdapterHandler.new(@document_store).list(folder_id)
        @vueops_documents_hashmap ||= @document_store.documents.inject({}){|hash, document| hash[document.file_id] = document; hash}
      else
        raise "Document store instance should not be nil"
      end
    end
  end
end

我的问题是 - 变量缓存范围何时结束?

根据您的设置,该方法的两次连续调用最终可能会在

中执行
  • 同一线程中的同一进程(记忆有效)
  • 不同线程中的相同进程(记忆有效)
  • 不同的进程(记忆不起作用)
  • 甚至不同 machine/vm(记忆不起作用)

如果工作人员使用 DocumentSynchronizers 的相同实例,则缓存将起作用,否则不会。

在您的情况下(扩展@Stefan 的评论)记忆不会带来任何好处,因为它在 initialize 方法中使用。该方法只执行一次没有执行之前可以设置值。所以和@variable = xxx.

没有区别

如果你这样使用,记忆化会更有意义:

class Something
  def value
    @value ||= some_expensive_calculation_that_can_be_cached
  end
end

然后不直接使用@value而是使用方法value。这有一个额外的好处,就是将计算推迟到您实际使用它(如果不总是使用它)