我的应用程序突然变得非常慢,响应时间可能长达 3 分钟。我尝试了两种不同的本地环境,以确保它不会因 CPU/RAM 或任何其他硬件组件而变慢,但问题仍然存在。
一些上下文
我正在使用 ruby 2.0.0 和 rails 4.0.0。 Pow 作为机架服务器和 PostgreSQL 数据库。
用于此测试的请求是一个基本的 API 调用,用于获取 entries
表中的所有条目。
表本身没有很多记录 (~12k)。
下面是该请求的日志显示内容:
Started GET "/en/*****/api/v1/entries.json" for 127.0.0.1 at 2014-09-11 11:42:13 +0100
ActiveRecord::SchemaMigration Load (0.7ms) SELECT "schema_migrations".* FROM "schema_migrations"
Processing by Api::V1::EntriesController#index as JSON
Parameters: {"subdomain"=>"cms", "not"=>[:new, :create, :edit, :update, :destroy], "locale"=>"en", "tenant"=>"*****"}
...
...
...
...
Completed 200 OK in 309341ms (Views: 307471.4ms | ActiveRecord: 1620.3ms)
是的,你读得很好...... View 渲染需要 299 秒。
条目操作
Api::V1::EntriesController#index 相当简单
def index
# Set Status
@status = params[:status].present? ? status_id("#{params[:status]}") : [0..3]
# Set Promoted
@promoted = params[:promoted].present? ? params[:promoted] : [true,false]
# Fetch Entries
@entries = Entry.where(status_id: @status, promoted: @promoted).filter_by_tag(params[:tag]).order("published_at DESC").paginate( page: params[:page], per_page: params[:limit] )
respond_with @entries
end
最后是 SQL 报告:
正如您在上面看到的,SQL 查询持续时间和时间戳不匹配。即使查询时间不长,时间戳也会增加得非常快(直到最后 300 秒)。 我将为您省去细节,但长长的查询列表(感谢 acts-as-taggable-on)没有显示任何奇怪或长时间的意外查询。最长的查询需要 300 毫秒。
开发.rb
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = true
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Do not compress assets
config.assets.compress = false
# Disable color for log file
config.colorize_logging = false
Pow 和 Rails 日志没有显示任何错误。我在我的以太网适配器的代理设置中绕过了 .dev。
知道什么会导致我的应用速度减慢那么多吗?
编辑#1
在呼吸暂停回复后,我删除了所有可能会减慢我的请求速度的关联。
现在可以简化呈现一个简单的 JSON 数组 ID(约 300 条记录)。
/app/controllers/api/v1/entries_controller.rb
def index
# Set Status
@status = params[:status].present? ? status_id("#{params[:status]}") : [0..3]
# Set Promoted
@promoted = params[:promoted].present? ? params[:promoted] : [true,false]
# Fetch entries
@entries = Entry.where(status_id: @status, promoted: @promoted)
respond_with @entries
end
/app/serializers/entry_serializer.rb
class EntrySerializer < ActiveModel::Serializer
attributes :id
end
对于这样一个简单的请求,结果仍然超过 3 秒......
Started GET "/en/*****/api/v1/entries.json?limit=2" for 127.0.0.1 at 2014-09-12 10:07:10 +0100
Processing by Api::V1::EntriesController#index as JSON
Parameters: {"limit"=>"2", "subdomain"=>"cms", "not"=>[:new, :create, :edit, :update, :destroy], "locale"=>"en", "tenant"=>"*****"}
Account Load (1.3ms) SELECT "accounts".* FROM "accounts" WHERE "accounts"."domain" = '******' ORDER BY "accounts"."id" ASC LIMIT 1
(0.6ms) BEGIN
SQL (2.2ms) INSERT INTO "sessions" ("cookie", "created_at", "domain", "locale", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["cookie", "Dn/aXXbbWG8t8A5ZYGVgsQ=="], ["created_at", Fri, 12 Sep 2014 09:07:11 UTC +00:00], ["domain", "*******"], ["locale", :en], ["updated_at", Fri, 12 Sep 2014 09:07:11 UTC +00:00]]
(0.6ms) COMMIT
ApiKey Load (0.6ms) SELECT "api_keys".* FROM "api_keys" WHERE "api_keys"."account_id" = 2 AND "api_keys"."access_token" IS NULL LIMIT 1
ApiKey Load (0.6ms) SELECT "api_keys".* FROM "api_keys" WHERE "api_keys"."account_id" = 2 AND "api_keys"."access_token" = '****************' LIMIT 1
Account Load (0.8ms) SELECT "accounts".* FROM "accounts" WHERE "accounts"."domain" = '*****' ORDER BY "accounts"."id" ASC LIMIT 1
SQL (2.6ms) UPDATE "api_keys" SET "count" = COALESCE("count", 0) + 1 WHERE "api_keys"."account_id" = 2 AND "api_keys"."id" = 2
Entry Load (4.9ms) SELECT "entries".* FROM "entries" WHERE "entries"."account_id" = 2 AND "entries"."promoted" IN ('t', 'f') AND (("entries"."status_id" BETWEEN 0 AND 3 OR 1=0))
Completed 200 OK in 3558ms (Views: 3246.6ms | ActiveRecord: 27.7ms)
条目表的索引:
# \d entries
Table "public.entries"
Column | Type | Modifiers
-------------------+-----------------------------+-------------------------------------------------------------------
id | integer | not null default nextval('entries_id_seq'::regclass)
title | character varying(255) |
slug | character varying(255) |
status_id | integer |
promoted | boolean |
published_at | timestamp without time zone | default '2014-07-31 15:06:20.462154'::timestamp without time zone
created_at | timestamp without time zone |
updated_at | timestamp without time zone |
account_id | integer |
excerpt | text |
user_id | uuid |
extra | hstore |
entry_views_count | integer |
Indexes:
"entries_pkey" PRIMARY KEY, btree (id)
"index_entries_on_slug" UNIQUE, btree (slug)
"entries_title" gin (to_tsvector('english'::regconfig, title::text))
"index_entries_on_account_id" btree (account_id)
"index_entries_on_promoted" btree (promoted)
"index_entries_on_status_id" btree (status_id)
"index_entries_on_user_id" btree (user_id)
最佳答案
你必须尽可能地预加载数据以防止 N+1 发生:
entries = Entry.where(status_id: @status, promoted: @promoted).filter_by_tag(params[:tag])
entries = entries.includes(:entry_fields).order("published_at DESC")
entries = entries.paginate( page: params[:page], per_page: params[:limit] )
包含
doc is here
关于ruby-on-rails - Rails API 请求非常慢 -> 300+ 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25789905/