Fragment_exist for Memcache does not find cached i

2019-08-04 10:19发布

问题:

I am using Rails, Dalli gem, friendly_id and Memcachier on Heroku.

My problem is similar to an issue I have had previously but that stopped working after I started using Memcache instead of the default Rails cache. It should be noted that I am not very familiar with Rails caching and it is quite likely that I do many things wrong (or fail to consider simple things).

production.rb

  config.action_controller.perform_caching = true
  config.cache_store = :dalli_store, 'mc2.ec2.memcachier.com:11211', { :namespace => 'my_app_name', :expires_in => 40.days, :compress => true, :username => 'asdf', :password => 'asdf' }

Gift#show - controller

unless fragment_exist?("gift-show--" + @gift.slug)
  # Perform slow database fetches etc
end

Gift#show - view

<% cache('gift-show--' + @gift.slug) do %>
 # Create HTML with lots of images and such
<% end %>

This worked fine before I started using Memcachier on Heroku. My guess is that fragment_exist? does not check in Memcachier but rather in "default Rails cache" (if there is a difference). I have tried to use Rails.cache.exist?("gift-show--" + @gift.slug) instead of fragment_exist? but it doesn't work.

I have loaded the particular gift#show-view a few times to make sure it is cached. In the logs I can also see Read fragment views/gift-show--cash-stash (1.3ms) (after the controller) which I believe is a proof for that a fragment actually exist. It is just that it is going through the slow (4 seconds) gift#show-controller when it is not necessary.

If I enter the console on Heroku and type "Rails.cache.read('gift-show--cash-stash')" I get a nil response.

Another peculiar things is that if do the following in the console:

irb(main):014:0> Rails.cache.write("foo", "bar")
=> true
irb(main):015:0> Rails.cache.read("foo")
=> nil

That is odd, isn't it?

So, what should I use, instead of fragment_exist? in order to make this work?

回答1:

I am not 100% sure this is the solution but I added the 'memcachier' gem (which I didn't have) and altered my production.rb to:

  config.cache_store = :dalli_store

This actually also solved another, completely different issue, to my great surprise!