0

在 Rails 应用程序中,单个 HTTP 请求中的唯一 SQL 语句的结果被缓存。如果同一语句在单个请求中运行两次,则缓存第二个查询。当在单个 HTTP 请求期间访问用户 18 两次时,这很好地导致以下结果:

User Load (0.6ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 18 LIMIT 1
CACHE (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 18 LIMIT 1

我可以在延迟的工作中做同样的事情吗?

4

1 回答 1

1

您可以选择性地打开(或关闭)代码块的缓存。您可以使用延迟作业使用的方法来执行此操作。

User.cache do 
  # caching is turned on in this block
  User.find(18)
  User.find(18)
end

User Load (0.6ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 18]]
CACHE (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 18]]

如果要禁用块的缓存:

User.uncached do
  # caching is off for this block
  User.find(18)
  User.find(18)
end

User Load (1.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]
User Load (0.5ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]
于 2013-07-03T21:12:07.317 回答