how to write a partial into a cache from a back gr

2019-07-14 17:45发布

Related to the question i have asked previously How to store a database intensive page into cache from a background process in rails

i want to write a partial into cache from a background process every 15 mins. And when ever a user request comes in i can just read the partial from the cache and render it and never explicitly expiring it.

Is there any ways to actually do it?

Thanks,

1条回答
成全新的幸福
2楼-- · 2019-07-14 18:15

I think what you want is to read the results of the db query with:

Rails.cache.fetch("key", :expires => 365.days) do
  # db query
end

and update it from a cron job 15 minutely with:

Rails.cache.write("key",
                  # db query
                  )

Then allow your partial to regenerate every 15 minutes as well (or every time even), since that's not the intensive part of the operation.

N.B.

  1. I'm setting :expires => 365.days in case you have a default expiry time set in your config and because I haven't looked up how to explicitly say 'never'.
  2. You need the query in the fetch block rather than just doing a read call so things don't break when the cron job has never been run, i.e. after a reboot. That is users will still be stuck waiting for it to load the first time the page gets hit after reboot/restart.
查看更多
登录 后发表回答