简体   繁体   中英

Rails 5 with memcached caching issue, wrong fragment cache is sticking even if I clear the cache

I have a Rails 5.2 app hosted on Heroku with Memcached cloud used, I have implemented multiple caching techniques in the app but one part of it has been very problematic & I tried to fix it for the past few days:

Fragment caching in one view had a design issue that I have fixed & then this design bug is still cached & delivered to users even after clearing the cache multiple times using:

Rails.cache.clear which gives me a correct output of clearing the cache like this:

irb(main):001:0> Rails.cache.clear
D, [2019-08-20T08:42:09.459517 #4] DEBUG -- : Dalli::Server#connect memcached-xxxxxxxxxx
I, [2019-08-20T08:42:09.596603 #4]  INFO -- : Dalli/SASL authenticating as memcached-appxxxxxx
I, [2019-08-20T08:42:09.598383 #4]  INFO -- : Dalli/SASL: Authenticated
=> [true]

The design bug is fixed for a page once I clear the cache (from Rails) then reload this page, however for other pages the wrong cache is still there until I find that (incorrectly cached) page, load it then it won't be fixed until I clear the cache again ...

It is now I have to find every single wrongly cached page , load it once (with the bad cache) & then clear the cache for it to work fine (as if I am clearing cache for one by one)

What is the correct way to fix this for all the cached pages at once?

Instead of expiring fragment caches, I'd recommend versioning them. eg instead of nav_header , you use a key like nav_header_v2 . Memcached will automatically clear content that doesn't get used, so the original fragments disappear to make room for the new ones. You never have to worry about clearing the cache.

You can go even further and automatically include a git version ID on all fragment keys, so they'll refresh when the code changes, eg nav_header_#{My::Application.config.git_commit}| .

This is the approach RailsGuides explains and ActiveRecord supports it via cache_key_with_version , so you can easily fragment-cache views of your models without having to clear them when the data changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM