I know Rails.cache
is ActiveSupport::Cache::MemoryStore
, and it is not thread safe.
I don't understand, why rails use a thread-unsafe cache as its default? W开发者_StackOverflowhy not use ActiveSupport::Cache::SynchronizedMemoryStore
? In my opinion, in a web site, if a cache is not thread-safe, it almost useless, because the requests are not handled in ONE thread.
Do you use Rails.cache
in you webapp? And how do you use it?
The default cache store in Rails is ActiveSupport::Cache::FileStore
, not MemoryStore
.
The memory store is of limited use in practice, since it is restricted to a single process, which makes it useless for Rails apps that are deployed using Passenger or a Mongrel cluster where requests are handled in separate processes, not in separate threads.
For small to medium-sized applications you'll probably do fine with the default file store. If you need to scale beyond that, you should have a look at ActiveSupport::Cache::MemCacheStore
.
Most deployment scenario's for Rails are actually single-threaded. Concurrency is achieved by spawning multiple processes, either automatically or beforehand. For many people, thread-safety won't matter that much.
Multi-threaded options do exist (especially with JRuby), so your question is still valid. Which is why in Rails 3, the old ActiveSupport::Cache::MemoryStore
has been removed and replaced with ActiveSupport::Cache::SynchronizedMemoryStore
, making it thread-safe by default.
If you need the thread-safety in a Rails 2 app, put the following somewhere in your environment.
ActionController::Base.cache_store = :synchronized_memory_store
The default Rails cache (ActiveSupport::Cache MemoryStore) is thread-safe as of Rails version 3.1: http://api.rubyonrails.org/v3.1.0/files/activesupport/CHANGELOG.html As the CHANGELOG notes: "Make thread safe so that the default cache implementation used by Rails is thread safe."
精彩评论