我如何 return 压缩 json 控制器中的 rails 数据?

How can i return compressed json data in rails controller itself?

我有一个api其中return庞大的数据,所以我想压缩这个数据并return给客户端。 我知道在 NginxRack::deflater in application.rb 中有一些方法可以做到。但是我只想为这个特定的 api 响应压缩这个数据。(不想在 ngnix 中这样做)

我尝试了这个答案中提到的:。 我能够压缩但无法使用压缩数据响应客户端。我试过了,想以某种方式 respond_to gz 作为响应类型。

Zlib::GzipWriter.open('public/huge_data.gz') { |gz| gz.write data.to_json }
    respond_to do |format|
      format.gz { render gz: {File.read('public/huge_data.gz') } }
    end

有什么方法可以将压缩后的数据传递给客户端或其他方法吗?提前致谢

我不推荐这样做,但如果你真的想手动压缩一个 JSON 响应,你可以这样做:

class CompressedController < ApplicationController
  def test
    respond_to do |f|
      f.json do
        file = Tempfile.new
        json = JSON.generate(hello: 'World')
        Zlib::GzipWriter.open(file.path) { |gz| gz.write json }
        response.set_header('Content-Encoding', 'gzip')
        send_data file.read, type: :json, disposition: 'inline'
      end
    end
  end
end

这只是一个独立的最小示例。根据您的实际用例进行调整。

如果您真的想以理智的方式解决性能问题,请在 Web 服务器层上与 caching 一起使用压缩。