【问题标题】:Why does User.first take more time to query the database for the first time?为什么 User.first 第一次查询数据库要花更多的时间?
【发布时间】:2014-06-09 10:37:13
【问题描述】:

当我打开现有应用程序的控制台并输入:

2.1.1 :001 > User.first
  User Load (17.6ms)  SELECT  "users".* FROM "users"   ORDER BY "users"."id" ASC LIMIT 1
=> #<User id: xxxx .... >

下次输入查询:

2.1.1 :002 > User.first
  User Load (0.8ms)  SELECT  "users".* FROM "users"   ORDER BY "users"."id" ASC LIMIT 1
=> #<User id: xxxx .... >

您可以看到rails查询数据库所用时间的差异。控制台中是否可用缓存之类的东西。这在运行的应用程序中的表现如何。是不是更多的时间,甚至是缓存,它到底是在哪里做的。

【问题讨论】:

    标签: ruby-on-rails ruby rails-console


    【解决方案1】:

    数据库服务器在查询缓存中缓存查询。

    有关 mysql 数据库查询缓存的文档请参见此处:https://dev.mysql.com/doc/refman/5.1/en/query-cache.html

    ActiveRecord 还执行查询缓存:

    http://edgeguides.rubyonrails.org/caching_with_rails.html

    这两种情况都可能发生,具体取决于您的系统配置。

    【讨论】:

    • 和较低级别的缓存,例如(在 mysql 的情况下)innodb 缓冲池等,表定义缓存等。
    【解决方案2】:

    如果您使用的是 rails 4,则不会立即建立数据库连接,直到您进行查询:

    2.1.1 :001 > User
     => User(no database connection) 
    2.1.1 :002 > User.first
    User Load (28.8ms)
    2.1.1 :003 > User.first
    User Load (1.9ms)
    2.1.1 :004 > User.last
    User Load (2.8ms)
    

    所以初始查询是建立数据库连接。之后的那些正在使用缓存(如其他答案中所述)并且已经建立了连接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-27
      • 1970-01-01
      • 1970-01-01
      • 2020-04-26
      • 2021-02-11
      • 1970-01-01
      • 2017-06-02
      • 2018-04-07
      相关资源
      最近更新 更多