Rails.cache在不同的线程中不能缓存? [英] Rails.cache in different threads not caching?
问题描述
Rails项目中的缓存方法结果有问题.
I have a problem with caching method results in rails project.
我来到了这段代码,它模拟了两个不同的请求:
I came to this code that simulates two different requests:
[
Thread.new { puts Rails.cache.fetch('a', expires_in: 2.seconds) { rand } },
Thread.new { puts Rails.cache.fetch('a', expires_in: 2.seconds) { rand } }
]
尝试在Rails控制台中执行它. 如果尝试在控制台中将其作为输出运行,则会得到不同的数字.那怎么可能?
Try to execute it in a rails console. If I try to run it in a console as output I get different numbers. How is that possible?
但是例如,此代码(带有睡眠)可以按预期工作:
But for example this code (with sleep) works as intended:
[
Thread.new { sleep(1); puts Rails.cache.fetch('a', expires_in: 2.seconds) { rand } },
Thread.new { puts Rails.cache.fetch('a', expires_in: 2.seconds) { rand } }
]
推荐答案
在第一个代码块中
[
Thread.new { puts Rails.cache.fetch('a', expires_in: 2.seconds) { rand } },
Thread.new { puts Rails.cache.fetch('a', expires_in: 2.seconds) { rand } }
]
我认为您的Rails配置正在使用文件进行缓存(为确保这一点,请检查Rails应用程序中的/tmp/cache文件夹).
I think your rails configuration is using file for caching (to ensure that, pls check the folder /tmp/cache in your rails app).
由于'Rails.cache'需要执行从文件读取缓存的操作,因此非常耗时,并且两个线程中的'fetch'操作大部分都在同一时间运行,因此'a'值不存在或为已经过期.
Because 'Rails.cache' needs to perform reading cache from file, it is time-consuming, and the action 'fetch' in 2 threads mostly run at the same time, so 'a' value doesn't exist or is expired already.
在第二个代码块中
[
Thread.new { sleep(1); puts Rails.cache.fetch('a', expires_in: 2.seconds) { rand } },
Thread.new { puts Rails.cache.fetch('a', expires_in: 2.seconds) { rand } }
]
当第一个线程尝试获取'a'时,'a'已经在缓存文件中.这就是它起作用的原因.
When the first thread tries to fetch 'a', 'a' is in cache file already. So that is why it works.
让我们进行另一个模拟,而不是使用"Rails.cache",我们将使用MemoryStore缓存,如下所示:
Let make another simulation, instead of using 'Rails.cache', we will use MemoryStore cache like this:
cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 5.minutes)
[
Thread.new { puts cache.fetch('a', expires_in: 2.seconds) { rand } },
Thread.new { puts cache.fetch('a', expires_in: 2.seconds) { rand } }
]
它也符合我们的期望!
这篇关于Rails.cache在不同的线程中不能缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!