[英]What's the most optimal way to regenerate static cache with Ruby on Rails?
I have a pretty slow controller action, which does some raporting here and there. 我的控制器动作很慢,到处乱跑。 I only need to refresh the data every few days, so it was no brainer to static cache the result. 我只需要每隔几天刷新一次数据,因此静态缓存结果并不费劲。
The problem is, that the action takes solid few minutes to complete and I am not sure whats the most optimal way to expire the old data and replace them with the new ones. 问题是,该操作需要几分钟的时间才能完成,而且我不确定使旧数据过期并用新数据替换它们的最佳方法是什么。
Now the problem with just generic expire/request is that for few minutes (time when the action is running) those data are unavailable. 现在,仅通用到期/请求的问题是几分钟(操作运行的时间)这些数据不可用。
Is there any resonable way to overcome this gap using just static cache mechanisms in Rails? 是否仅在Rails中使用静态缓存机制就可以克服这种差距? Or should I just rebuild the whole thing in a different way? 还是我应该以另一种方式重建整个事情?
Rails has a built-in way to use stale caches for just a bit longer when it expires while the new cache value is being regenerated. 在重新生成新的缓存值时,Rails有过期的过期时间,Rails具有一种内置的使用方式。 It's the :race_condition_ttl
setting used in conjuction with :expires_in
, as describe in the Rails Guides on Caching . 这是:race_condition_ttl
设置与:expires_in
结合使用,如《 Rails缓存指南》中所述。
With Rails Fragment caching the syntax should be: 使用Rails Fragment缓存时,语法应为:
<% cache 'my_awesome_cache_key', :expires_in => 12.hours.to_i, :race_condition_ttl => 12.hours.to_i %>
# This block will be cached
<% end %>
Results: 结果:
race_condition_ttl
was introduced to prevent multiple processes from regenerating a cache simultaneuosly, which would result in all processes reading the data from the db at once etc. on a highly requested resource, but I think it should work well for your situation. 引入race_condition_ttl
是为了防止多个进程同时重新生成高速缓存,这将导致所有进程立即从数据库中读取大量请求的资源,等等,但是我认为它应该适合您的情况。
How to choose the timing for :expires_in
and :race_condition_ttl
is your choice then, I'd suggest calculating it like this: expires_in + race_condition = expires_in_that_you_would_usually_set
. 然后,如何选择:expires_in
和:race_condition_ttl
是您的选择,我建议按以下方式进行计算: expires_in + race_condition = expires_in_that_you_would_usually_set
。 This way the cache is regenerated more often but also fresher, especially if the action/view is not rendered that often. 这样,可以更频繁地重新生成缓存,但是也可以更新缓存,特别是如果操作/视图的显示频率不那么高的话。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.