Rails 关于 Rails 的缓存(ActiveSupport::Cache::Strategy::LocalCache 该怎么用?)

hiveer · July 28, 2014 · Last by hiveer replied at July 28, 2014 · 3383 hits

ActiveSupport::Cache::Strategy::LocalCache 这个中间件是干嘛的?是不是 Rails 会默认用来存什么东西,或者我们需要用的话该怎么用呢?

自己顶一下!

自己研究了下,下面是一些成果

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

然后解释下上面的代码,如果我们把平时使用缓存的代码,比如 Rails.cache.write('name', 'key') 作为方法 with_local_cache 的参数,那么最终会产生一个结果,那就是会有两个地方缓存了这对 key,value。一个地方就是 LocalCache,另一个地方就是我们指定的 Rails 缓存。

有了以上的这些理解,我们再来看看官方的解释

Caches that implement LocalCache will be backed by an in-memory cache for the

duration of a block. Repeated calls to the cache for the same key will hit the

in-memory cache for faster access.

是不是有一种恍然大悟的感觉!

不得不感叹!不是别人的代码太晦涩,只是因为我们看不懂注释!

You need to Sign in before reply, if you don't have an account, please Sign up first.