跳至内容 跳至搜索

Action Controller Live

将此模块混入到您的控制器中,该控制器中的所有操作都将能够随着数据的写入而将数据流式传输到客户端。

class MyController < ActionController::Base
  include ActionController::Live

  def stream
    response.headers['Content-Type'] = 'text/event-stream'
    100.times {
      response.stream.write "hello world\n"
      sleep 1
    }
  ensure
    response.stream.close
  end
end

此模块有一些注意事项。响应被提交后(Response#committed? 将返回真值),您不能再写入标头。对响应流调用 writeclose 将导致响应对象被提交。请确保在对流调用 write 或 close 之前设置好所有标头。

完成流处理后,您必须调用 stream 的 close 方法,否则套接字可能会永远保持打开状态。

最后的注意事项是,您的操作将在与主线程不同的线程中执行。请确保您的操作是线程安全的,这样就不会有问题(不要跨线程共享状态等)。

请注意,Rails 默认包含 Rack::ETag,它会缓冲您的响应。因此,流式响应可能无法在 Rack 2.2.x 中正常工作,您可能需要在应用程序中实现变通方法。您可以设置 ETagLast-Modified 响应标头,或从中间件堆栈中删除 Rack::Etag 来解决此问题。

以下是如何在 Rack 版本为 2.2.x 时设置 Last-Modified 标头的示例

def stream
  response.headers["Content-Type"] = "text/event-stream"
  response.headers["Last-Modified"] = Time.now.httpdate # Add this line if your Rack version is 2.2.x
  ...
end
命名空间
方法
L
P
R
S

类公共方法

live_thread_pool_executor()

# File actionpack/lib/action_controller/metal/live.rb, line 375
def self.live_thread_pool_executor
  @live_thread_pool_executor ||= Concurrent::CachedThreadPool.new(name: "action_controller.live")
end

实例公共方法

process(name)

# File actionpack/lib/action_controller/metal/live.rb, line 266
def process(name)
  t1 = Thread.current
  locals = t1.keys.map { |key| [key, t1[key]] }

  error = nil
  # This processes the action in a child thread. It lets us return the response
  # code and headers back up the Rack stack, and still process the body in
  # parallel with sending data to the client.
  new_controller_thread do
    ActiveSupport::Dependencies.interlock.running do
      t2 = Thread.current

      # Since we're processing the view in a different thread, copy the thread locals
      # from the main thread to the child thread. :'(
      locals.each { |k, v| t2[k] = v }
      ActiveSupport::IsolatedExecutionState.share_with(t1) do
        super(name)
      rescue => e
        if @_response.committed?
          begin
            @_response.stream.write(ActionView::Base.streaming_completion_on_exception) if request.format == :html
            @_response.stream.call_on_error
          rescue => exception
            log_error(exception)
          ensure
            log_error(e)
            @_response.stream.close
          end
        else
          error = e
        end
      ensure
        clean_up_thread_locals(locals, t2)

        @_response.commit!
      end
    end
  end

  @_response.await_commit

  raise error if error
end

response_body=(body)

# File actionpack/lib/action_controller/metal/live.rb, line 310
def response_body=(body)
  super
  response.close if response
end

send_stream(filename:, disposition: "attachment", type: nil)

将流发送到浏览器,这在生成不需要将整个文件预先缓冲在内存中的导出或其他运行数据时非常有用。与 send_data 类似,但数据是实时生成的。

选项:

  • :filename - 建议浏览器使用的文件名。

  • :type - 指定 HTTP 内容类型。您可以指定一个字符串或一个符号,用于 Mime::Type.register 注册的类型,例如 :json。如果省略,类型将从 :filename 中指定的文件扩展名推断。如果扩展名没有注册内容类型,则将使用默认类型 ‘application/octet-stream’。

  • :disposition - 指定文件是内联显示还是下载。有效值为 ‘inline’ 和 ‘attachment’(默认)。

生成 csv 导出的示例

send_stream(filename: "subscribers.csv") do |stream|
  stream.write "email_address,updated_at\n"

  @subscribers.find_each do |subscriber|
    stream.write "#{subscriber.email_address},#{subscriber.updated_at}\n"
  end
end
# File actionpack/lib/action_controller/metal/live.rb, line 340
def send_stream(filename:, disposition: "attachment", type: nil)
  payload = { filename: filename, disposition: disposition, type: type }
  ActiveSupport::Notifications.instrument("send_stream.action_controller", payload) do
    response.headers["Content-Type"] =
      (type.is_a?(Symbol) ? Mime[type].to_s : type) ||
      Mime::Type.lookup_by_extension(File.extname(filename).downcase.delete("."))&.to_s ||
      "application/octet-stream"

    response.headers["Content-Disposition"] =
      ActionDispatch::Http::ContentDisposition.format(disposition: disposition, filename: filename)

    yield response.stream
  end
ensure
  response.stream.close
end