【问题标题】:What is ActiveSupport::Cache::Strategy::LocalCache used for?ActiveSupport::Cache::Strategy::LocalCache 是做什么用的?
【发布时间】:2013-11-19 01:01:39
【问题描述】:

在所有环境中的生产中间件堆栈中,我都看到了这个一次性实例:

use #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x7f38095d>

我已经尝试删除所有我能想到的与缓存相关的内容,但我无法弄清楚它来自哪里。

这是什么?

【问题讨论】:

    标签: ruby-on-rails rack rack-middleware


    【解决方案1】:

    在抽象中,它在一个块的持续时间内用内存中的缓存包装另一个缓存,然后在块之后被清除。

    在实践中,我相信它在 Rails/Rack 中用于将您配置的任何缓存(memcached、磁盘)与在请求结束时清除的内存缓存进行包装。这个想法是,如果您在一个请求中两次获取相同的缓存键,它将在第一个请求时缓存在包装 LocalCache 中,并在第二个请求时从内存中加载(而不是再次访问 memcached 服务器/磁盘) .

    来自文档:

    实现 LocalCache 的缓存将在一个块的持续时间内由内存中的缓存支持。对同一个键的缓存重复调用将命中内存缓存以加快访问速度。

    Git 历史: https://github.com/rails/rails/commits/master/activesupport/lib/active_support/cache/strategy/local_cache.rb

    RDoc: http://api.rubyonrails.org/classes/ActiveSupport/Cache/Strategy/LocalCache.html

    【讨论】:

      【解决方案2】:

      首先,我想向您展示一些官方文档中的方法。

      ActiveSupport::Cache::DalliStore#with_local_cache
      
      def with_local_cache
        use_temporary_local_cache(LocalStore.new) { yield }
      end
      
      def use_temporary_local_cache(temporary_cache)
        save_cache = LocalCacheRegistry.cache_for(local_cache_key)
        begin
          LocalCacheRegistry.set_cache_for(local_cache_key, temporary_cache)
          yield
        ensure
          LocalCacheRegistry.set_cache_for(local_cache_key, save_cache)
        end
      end
      
      def write(name, value, options=nil)
        options ||= {}
        name = expanded_key name
      
        instrument(:write, name, options) do |payload|
          with do |connection|
            options = options.merge(:connection => connection)
            write_entry(name, value, options)
          end
        end
      end
      
      def write_entry(key, entry, options) # :nodoc:
        local_cache.write_entry(key, entry, options) if local_cache
        super
      end
      

      现在,我们在实践中使用它们。

      @cache = Rails.cache
      @cache.with_local_cache do
         @cache.write('key', 'value')
      end
      

      如果你结合上面的代码,你会发现应该有两个地方缓存了('key', 'value') 对。一个是LocalCache,另一个是我们的@cache。它的目的在源代码中明确地声明了。

      实现 LocalCache 的缓存将由内存缓存支持 块的持续时间。重复调用同一个键的缓存会命中 内存缓存以加快访问速度。

      希望对你有所帮助!

      【讨论】:

        猜你喜欢
        • 2019-03-31
        • 1970-01-01
        • 1970-01-01
        • 2023-03-29
        • 2015-11-25
        • 2011-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多