Expiring Key Cache

I am working on a mashup site and want to limit the number of selections in order to clean up the source sites. There is essentially one bit of data that I need, an integer, and would like to cache it with a specific expiration period.

To clarify, I only want to cache an integer, not the entire page source.

Is there a ruby ​​or rail function or a gem that already does this for me?

+4
source share
2 answers

Yes, there is ActiveSupport::Cache::Store

Abstract cache storage class. There are several cache repositories that have their own additional features. See classes in the ActiveSupport :: Cache module, for example. ActiveSupport :: Cache :: MemCacheStore. MemCacheStore is currently the most popular cache drive for large production sites.

Some implementations may not support all methods that go beyond the basic cache methods of extraction, writing, reading, existence? and deletion.

ActiveSupport :: Cache :: Store can store any Ruby serializable object.

http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html

 cache = ActiveSupport::Cache::MemoryStore.new cache.read('Chicago') # => nil cache.write('Chicago', 2707000) cache.read('Chicago') # => 2707000 

As for the expiration time, this can be done by passing the time as an initialization parameter

 cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 5.minutes) 

If you want to cache a value with a different expiration time, you can also set this when writing the value to the cache

 cache.write(key, value, expires_in: 1.minute) # Set a lower value for one entry 
+9
source

See Caching with rails , in particular the parameter :expires_in for ActiveSupport::Cache::Store .

For example, you can go:

 value = Rails.cache.fetch('key', expires_in: 1.hour) do expensive_operation_to_compute_value() end 
+2
source

Source: https://habr.com/ru/post/1496406/


All Articles