Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to store an ActiveRecord object in memcached?

There are currently two problems with storing ActiveRecord objects in memcached.

  1. The Undefined Class/Module problem (Google search). From what I've read up, this is still a bug that nobody has a real good solution for. The cache_fu plugin has probably the best solution for this, wrapping its retrieve call in a block that tries to catch this error, parses the message and tries to load the undefined class/module.

  2. The infamous LH ticket #1339 (LH Ticket). This bug will only happen when you have cache_classes set to FALSE (development, test).

After googling for weeks, I still haven't found a good technique for storing AR instances in memcached without having to deal with the 2 issues listed above.

The idea I haven't tried yet is removing the attributes from the instance as strings (just how AR receives them from the DB before it does its type casting), storing those in memcached and then on retrieval from the cache, somehow instantiate an AR object using these values. Is this possible? If so, what is the best way to do it?

I'm just looking for ways other Rails developers have tackled this problem.

like image 309
Jose Fernandez Avatar asked Mar 06 '10 20:03

Jose Fernandez


People also ask

Where is Rails cache stored?

Page caches are always stored on disk. Rails 2.1 and above provide ActiveSupport::Cache::Store which can be used to cache strings. Some cache store implementations, like MemoryStore, are able to cache arbitrary Ruby objects, but don't count on every cache store to be able to do that.

How does memcached work in Rails?

Memcache caches objects in RAM to speed up access to the content. Content is directly fetched from memory instead of from an external data source. One of the most popular memcache servers is provided by Danga, an open-source software.

How does Rails query cache work?

Query caching is a Rails feature that caches the result set returned by each query. If Rails encounters the same query again for that request, it will use the cached result set as opposed to running the query against the database again.

What are view caches?

View caching in Ruby on Rails is taking the HTML that a view generates and storing it for later.


1 Answers

In our projects we store the object as XML.

cache.write(user.cache_key, user.to_xml) # write to cache
User.new(Hash.from_xml(cache.read(cache_key))) # reach from cache xml

There is some extra cost for serializing/de-serializing XML. But this has enabled us to share the cache amongst non Ruby apps.

like image 87
Harish Shetty Avatar answered Oct 07 '22 14:10

Harish Shetty