【问题标题】:Inefficient memory usage when using object.get使用 object.get 时内存使用效率低下
【发布时间】:2021-03-24 13:46:36
【问题描述】:

我认为当将 s3 对象下载到文件中时,它会分块写入,以避免将整个文件加载到内存中。

但显然情况并非如此,这是我的代码:

puts("Memory (before file loaded): #{((`ps -o rss= -p #{Process.pid}`.to_i) / 1024.0).round(2)} MB")
my_s3_object.get(response_target: file_path)
puts("Memory (after file loaded): #{((`ps -o rss= -p #{Process.pid}`.to_i) / 1024.0).round(2)} MB")

输出:

Memory (before file loaded): 191.08 MB
Memory (after file loaded): 259.41 MB

my_s3_object 是 130MB 的 zip 存档。好的,所以它没有完全加载到内存中,但几乎是一半。

有没有办法通过将一些参数传递给get 方法来提高内存使用率?或者我该怎么做?

【问题讨论】:

    标签: ruby amazon-web-services amazon-s3


    【解决方案1】:

    我认为您正在寻找范围请求,这是一种“通用”HTTP“模式”并受 AWS 开发工具包支持。

    documentation 提供了以下示例,这些示例应允许您下载对象的部分内容、写入它们、从内存中丢弃字节并读取下一个字节,直到下载整个文件。最后,内存使用量将取决于您每次请求下载的字节范围。

    示例:检索对象的字节范围

    
    # The following example retrieves an object for an S3 bucket. 
    # The request specifies the range header to retrieve a specific 
    # byte range.
    
    resp = client.get_object({
      bucket: "examplebucket", 
      key: "SampleFile.txt", 
      range: "bytes=0-9", 
    })
    
    resp.to_h outputs the following:
    {
      accept_ranges: "bytes", 
      content_length: 10, 
      content_range: "bytes 0-9/43", 
      content_type: "text/plain", 
      etag: "\"0d94420ffd0bc68cd3d152506b97a9cc\"", 
      last_modified: Time.parse("Thu, 09 Oct 2014 22:57:28 GMT"), 
      metadata: {
      }, 
      version_id: "null", 
    }
    

    将数据流式传输到块

    # WARNING: yielding data to a block disables retries of networking errors
    # However truncation of the body will be retried automatically using a range request
    File.open('/path/to/file', 'wb') do |file|
      s3.get_object(bucket: 'bucket-name', key: 'object-key') do |chunk, headers|
        # headers['content-length']
        file.write(chunk)
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2019-01-23
      • 2014-05-04
      • 2018-05-02
      • 1970-01-01
      • 2011-08-24
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多