【问题标题】:Why do I have Rails views overhead when handling API requests?为什么在处理 API 请求时会有 Rails 视图开销?
【发布时间】:2021-08-06 21:19:55
【问题描述】:

我在我的日志中注意到,当我访问 API 端点时,内置分析的 Rails 报告它在“视图”中花费了 一些 时间(heroku 额外的日志信息已删除):

[2021-08-06T21:04:20.864743 #32]  INFO -- : Started POST "/api/v1/places_in_bounds" for 24.184.254.41 at 2021-08-06 21:04:20 +0000
[2021-08-06T21:04:20.865565 #32]  INFO -- : Processing by Api::V1::PlacesController#in_bounds as */*
[2021-08-06T21:04:20.865629 #32]  INFO -- : Parameters: {"place"=>{"east"=>-38.800911000000006, "north"=>62.13593387702106, "south"=>-109.113411, "west"=>9.516666266458477}}
[2021-08-06T21:04:20.903245 #32]  INFO -- : Completed 200 OK in 37ms (Views: 26.8ms | ActiveRecord: 2.3ms | Allocations: 28475)

...但我没有渲染任何视图!它是一个 API 端点,而不是 erb。这是怎么回事?我的jsonapi-serializer 序列化程序算作浏览量吗?除了破解 open rails 本身或分析 ruby​​ 解释器之外,我还不清楚发生了什么。这不是很大的开销(通常远低于 50%),但想必这个答案对其他人有用!

【问题讨论】:

    标签: ruby-on-rails rails-api


    【解决方案1】:

    简短的回答是肯定的,因为您在控制器中调用了 render

    ActionController::BaseActionController::API 都包含 ActionController::Instrumentation,它将 render 包装在基准测试中:

    def render(*)
      render_output = nil
      self.view_runtime = cleanup_view_runtime do
        Benchmark.ms { render_output = super }
      end
      render_output
    end
    

    因此,无论您呈现什么格式,它都会捕获并记录运行时:

    def log_process_action(payload) #:nodoc:
      messages, view_runtime = [], payload[:view_runtime]
      messages << ("Views: %.1fms" % view_runtime.to_f) if view_runtime
      messages
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-25
      • 1970-01-01
      • 2018-10-03
      • 1970-01-01
      • 2013-09-10
      • 2023-03-10
      相关资源
      最近更新 更多