Date post: | 28-Jan-2018 |
Category: |
Software |
Upload: | vysakh-sreenivasan |
View: | 570 times |
Download: | 1 times |
Caching in RailsVysakh Sreenivasan
Only 2 hard Problems in CS
● Naming
● Cache invalidation
Caching in a web app● Prevent hitting databases.
● Cache the html responses.
● Help browser implement caching.
Before implementing caching we need a cache server
Memcached is the popular cache server
sudo apt-get install memcached
Before implementing caching in Rails we need to configure
config.action_controller.perform_caching = true
Using memcached with Rails 4.0
● gem ‘dalli’
● config.cache_store = :mem_cache_store
Lets get to the implementation
#1 Model level caching
Rails.cache.fetch
● First time, it can’t fetch a cache, so it will write a cache.
● Then it reads those caches.
Rails.cache.delete
● When passed an argument, it deletes the specific cache.
● You can clear caches in hooks like after_save
You can also use this to cache API results
#2 Fragment caching
<% cache @post do %>
<h3> <%= @post.title %> </h3>
<% end %>
cache_key: views/posts/1-201505056193031061005000/bea67108094918eeba42cd4a6e786901
based on @post.cache_key which is based on updated_at
md5 hash based on the view’s contents
Cache key changes when
● the record is updated -> a new cache_key is formed
● the view is changed -> a new md5 key is generated
The old keys will be there, which will be removed
automatically by memcached
#3 http caching
e-tag & 304 not modified
fresh_when(@post)
# or
fresh_when(etag: @post , last_modified: @post.updated_at)
based on @post.cache_key which is based on updated_at
if stale?(@post)
respond_to do |f|
…
end
end
Alternate syntax. Especially when using respond_to
def show
@post = Post.first
expires_in 5.minutes
end
Cache control: max_age
Recap1 Model level
● Rails.cache.fetch
● Rails.cache.delete
2 Fragment
<% cache @post do %>
<% end %>
3. etags
if stale?(@post)
Resources
● Docs: http://guides.rubyonrails.org/caching_with_rails.html
● Railscasts episodes on http caching, low level caching,
cache digests, dalli gem.