ちょっと話題の記事

AWS SDK for Ruby を使ってコンテンツを S3 に gzip 圧縮して保存する

2014.08.08

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

S3 でコンテンツを gzip に対応させる方法は、オブジェクトの Metadata に対して、Content-Encoding を指定できるのでここに指定します。

140808-0002

Ruby の AWS SDK Core を使ってアップロードとダウンロードを試してみました。

アップロード

アップロードするスクリプトは以下です。

require 'tempfile'
require 'active_support/gzip'
require 'aws-sdk-core'

temp = Tempfile.new('sample')
temp.print 'test ' * 100

temp.rewind
gzip_data = ActiveSupport::Gzip.compress(temp.gets)
temp.close

s3 = Aws::S3::Client.new(region: 'ap-northeast-1')
s3.put_object(
  acl: 'public-read',
  bucket: 'bucket-name',
  content_type: 'application/text; charset=UTF-8',
  content_encoding: 'gzip',
  key: 'sample.txt',
  body: gzip_data
)

ActiveSupport::Gzip で圧縮し、content_encoding に gzip を指定しています。

ダウンロード

ダウンロードを試すスクリプトは以下です。

require 'httpclient'

client = HTTPClient.new
res = client.get_content(
  'http://s3-ap-northeast-1.amazonaws.com/bucket-name/sample.txt'
)

puts "response: #{res}"
puts "size: #{res.size}"

HTTPClient を使ってますが、このままだと以下のように文字化けします。

response: tO�S+I-.Q(%F�Y�
size: 30

圧縮されているので、サイズも少ないですね。

次は、ちゃんと gzip に対応させて試してみます。

require 'httpclient'

client = HTTPClient.new
client.transparent_gzip_decompression = true
res = client.get_content(
  'http://s3-ap-northeast-1.amazonaws.com/bucket-name/sample.txt'
)

puts "response: #{res}"
puts "size: #{res.size}"
response: test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test
size: 500

今度は上手くいきました。

まとめ

短いですが、S3 での gzip のお話でした。
ちなみに、Google Developers によるとオーバーヘッドが発生するため、 圧縮するファイルサイズの最小範囲は 150 〜 1000 バイトが推奨されています。

https://developers.google.com/speed/docs/best-practices/payload?hl=ja#GzipCompression