gpt4 book ai didi

ruby-on-rails - 适当的Rails低级缓存并发

转载 作者:行者123 更新时间:2023-12-03 13:19:10 25 4
gpt4 key购买 nike

我想在Puma上运行我的Rails 5应用程序。我使用低级缓存,并假设具有线程安全缓存的方式:

# somewhere in a model ...

@@mutex = Mutex.new

def nice_suff
Rails.cache.fetch("a_key") do
@@mutex.synchronize do
Rails.cache.fetch("a_key", 60) do
Model.stuff.to_a
end
end
end
end

这样会很好吗?

最佳答案

处理并发缓存访问的正确方法已经内置。

  val_1 = cache.fetch('foo', race_condition_ttl: 10.seconds) do
Model.stuff.to_a
end

Setting :race_condition_ttl is very useful in situations where a cache entry is used very frequently and is under heavy load. If a cache expires and due to heavy load several different processes will try to read data natively and then they all will try to write to cache. To avoid that case the first process to find an expired cache entry will bump the cache expiration time by the value set in :race_condition_ttl. Yes, this process is extending the time for a stale value by another few seconds. Because of extended life of the previous cache, other processes will continue to use slightly stale data for a just a bit longer. In the meantime that first process will go ahead and will write into cache the new value. After that all the processes will start getting the new value. The key is to keep :race_condition_ttl small.

关于ruby-on-rails - 适当的Rails低级缓存并发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43837027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com