[英]Please explain the behaviour of Rails's cache in this case
假設我有 5 個標簽: tag1,tag2...tag5
。 如果我執行以下操作:
Rails.cache.fetch("all.tags") { Tag.all }
然后我寫Rails.cache.fetch("all.tags")
,我看到了 5 個標簽。 如果我添加另一個標簽,並嘗試再次從緩存中獲取,新標簽也會被加載。 這是為什么?
編輯:這是我的實際代碼:
Rails.cache.fetch("autocomplete.#{term}") { puts "Cache miss #{term}"; Tag.starting_with(term) }
where starting_with
正在做一個在哪里可以找到以特定字母開頭的標簽。 這是我在控制台中得到的行為:
1.9.3p125 :046 > Rails.cache.read("autocomplete.ta")
Tag Load (1.0ms) SELECT "tags".* FROM "tags" WHERE (name like 'ta%')
=> [#<Tag id: 10, name: "tag1">, #<Tag id: 11, name: "tag2">, #<Tag id: 12, name: "tag3">, #<Tag id: 13, name: "tag4">]
1.9.3p125 :048 > Tag.create(name:"tag5")
(0.2ms) begin transaction
SQL (1.0ms) INSERT INTO "tags" ("name") VALUES (?) [["name", "tag5"]]
(150.9ms) commit transaction
=> #<Tag id: 14, name: "tag5">
1.9.3p125 :049 > Rails.cache.read("autocomplete.ta")
Tag Load (0.8ms) SELECT "tags".* FROM "tags" WHERE (name like 'ta%')
=> [#<Tag id: 10, name: "tag1">, #<Tag id: 11, name: "tag2">, #<Tag id: 12, name: "tag3">, #<Tag id: 13, name: "tag4">, #<Tag id: 14, name: "tag5">]
這是不可能的。
緩存在鍵/值對上工作。
Rails.cache.fetch("all.tags") { Tag.all }
它將始終返回存儲鍵“all.tags”的值。
您能否嘗試讀取存儲在緩存中的值。 然后添加新標簽
Rails.cache.read("all.tags")
我知道這不是您問題的答案,但我也很想知道為什么會這樣。
你還在用緩存設置做其他事情嗎?
您沒有顯示Tag.starting_with_term
的代碼,但我敢打賭它是 scope 或返回 scope 之類的東西,即類似於
Tag.where(...)
這與您最初的問題中的Tag.all
根本不同: Tag.all
是一個數組,但上面是一個 scope。作用域是延遲評估的,只有當您在 scope 上調用需要的方法時,才會從數據庫請求行scope 是一個實際的數組。
這里發生的事情是您正在緩存實際的 scope,而不是 scope 將 select 的行。另一種看待它的方式是說目前您正在緩存構成查詢的條件,而不是查詢結果。
當您從緩存中讀取時,您的 scope 將從緩存中檢索出來,並且嘗試顯示它的行為會強制 Rails 對其求值。 此評估發生在從緩存中檢索到 scope 之后,因此您始終可以獲得最新結果。
最簡單的事情是強制評估 scope,即類似於
Rails.cache.fetch('cache_key') { Tag.starting_with(term).all }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.