gpt4 book ai didi

ruby-on-rails - 如何为单个请求或代码块绕过 Rails.cache?

转载 作者:数据小太阳 更新时间:2023-10-29 08:03:59 32 4
gpt4 key购买 nike

我有一个 API 端点,该端点从利用 Rails.cache 的代码中收集大量数据,用于各处的小块数据。然而,有时我想要 100% 最新的数据,就好像 Rails.cache 是空的一样。显然,我可以在聚合数据之前清除缓存,但这会影响不相关的数据和请求。

有没有办法让我在 Rails 中发出请求,就像 Rails.cache 是空的一样,类似于 Rails.cache 配置为:null_store?

ActiveRecord 中的查询缓存有类似这样的东西——一个“未缓存”的函数,你可以将一个 block 传递给它, block 将在没有启用查询缓存的情况下运行。我需要类似的东西,但通常用于 Rails.cache。

最佳答案

由于似乎没有开箱即用的解决方案,我通过将以下代码添加为 config/initializers/rails_cache.rb 编写了自己的解决方案

module Rails
class << self
alias :default_rails_cache :cache
def cache
# Allow any thread to override Rails.cache with its own cache implementation.
RequestStore.store[:rails_cache] || default_rails_cache
end
end
end

这允许任何线程指定其自己的缓存存储,然后将其用于所有提取、读取和写入。因此,它不会从默认的 Rails.cache 中读取,也不会将其值写入默认的 Rails.cache。

如果线程长时间运行并且受益于启用缓存,您可以轻松地将其设置为它自己的 MemoryStore 实例:

RequestStore.store[:rails_cache] = ActiveSupport::Cache.lookup_store(:memory_store)

如果你想完全关闭这个线程的缓存,你可以 :null_store 而不是 :memory_store。

如果您没有使用 request_store gem,可以将“RequestStore.store”替换为“Thread.current”以达到相同的效果 - 只是需要更加注意跨请求的线程重用。

关于ruby-on-rails - 如何为单个请求或代码块绕过 Rails.cache?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26223446/

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