ストリーミング読み取り

Cloud Storage ではオブジェクトの読み取りのストリーミングがサポートされています。これにより、アプリケーションやプロセスは、データをローカル ディスクや永続ストレージに保存することなく、ネットワーク接続を介してオブジェクトのバイトストリームをリアルタイムで消費できます。

オブジェクトをダウンロードしてローカル ファイル システムに保存する場合は、代わりに ファイルをダウンロードするをご覧ください。

読み取りのストリーミング時にチェックサム検証を使用する

データ処理の前にチェックサム検証 が必要な場合は、読み取りのストリーミングを使用しないでください。読み取りのストリーミングでは通常、HTTP Range ヘッダーが使用されるため、Cloud Storage は、オブジェクト データのリクエストされた任意の部分にのみ適用されるチェックサムを返しません。サーバーのチェックサムはオブジェクト全体を検証します。つまり、ストリーム全体が完了して検証される前に、破損したデータが読み取られて処理される可能性があります。

必要なロール

読み取りのストリーミングに必要な権限を取得するには、バケットに対するストレージ オブジェクト閲覧者(roles/storage.objectViewer)ロールを付与するよう管理者に依頼してください。

このロールには、読み取りのストリーミングに必要な権限が含まれています。必要とされる正確な権限については、必要な権限 のセクションを開いてご確認ください。

必要な権限

  • storage.objects.get

この権限は、他の事前定義ロールやカスタムロールから取得することもできます。

バケットに対するロールを付与する手順については、 バケットでの IAM ポリシーの設定と管理をご覧ください。

オブジェクトの読み取りをストリーミングする

次の例は、Cloud Storage オブジェクトからプロセスへのストリーミング読み取りを実行する方法を示しています。

Console

コンソール Google Cloud では、読み取りのストリーミングはサポートされていません。代わりに Google Cloud CLI を使用してください。

コマンドライン

  1. リンク先 URL にダッシュを使用して gcloud storage cp コマンドを実行し、データをプロセスに連結します。

    gcloud storage cp gs://BUCKET_NAME/OBJECT_NAME - | PROCESS_NAME

    ここで

    • BUCKET_NAME は、オブジェクトを含むバケットの名前です。例: my_app_bucket
    • OBJECT_NAME は、プロセスにストリーミングするオブジェクトの名前です。例: data_measurements
    • PROCESS_NAME は、データをフィードするプロセスの名前です。例: analyze_data

Cloud Storage オブジェクトのデータを、sort などの Linux の標準コマンドに ストリーミングすることもできます。

gcloud storage cp gs://my_app_bucket/data_measurements - | sort

クライアント ライブラリ

C++

詳細については、 Cloud Storage C++ API リファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name) {
  gcs::ObjectReadStream stream = client.ReadObject(bucket_name, object_name);

  int count = 0;
  std::string line;
  while (std::getline(stream, line, '\n')) {
    ++count;
  }
  if (stream.bad()) throw google::cloud::Status(stream.status());

  std::cout << "The object has " << count << " lines\n";
}

C#

詳細については、 Cloud Storage C# API リファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。


using Google.Cloud.Storage.V1;
using System;
using System.IO;

public class DownloadFileSample
{
    public void DownloadFile(
        string bucketName = "your-unique-bucket-name",
        string objectName = "my-file-name",
        string localPath = "my-local-path/my-file-name")
    {
        var storage = StorageClient.Create();
        using var outputFile = File.OpenWrite(localPath);
        storage.DownloadObject(bucketName, objectName, outputFile);
        Console.WriteLine($"Downloaded {objectName} to {localPath}.");
    }
}

Go

詳細については、 Cloud Storage Go API リファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。


import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// downloadFileIntoMemory downloads an object.
func downloadFileIntoMemory(w io.Writer, bucket, object string) ([]byte, error) {
	// bucket := "bucket-name"
	// object := "object-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*50)
	defer cancel()

	rc, err := client.Bucket(bucket).Object(object).NewReader(ctx)
	if err != nil {
		return nil, fmt.Errorf("Object(%q).NewReader: %w", object, err)
	}
	defer rc.Close()

	data, err := io.ReadAll(rc)
	if err != nil {
		return nil, fmt.Errorf("io.ReadAll: %w", err)
	}
	fmt.Fprintf(w, "Blob %v downloaded.\n", object)
	return data, nil
}

Java

詳細については、 Cloud Storage Java API リファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。


import com.google.cloud.ReadChannel;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.common.io.ByteStreams;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class StreamObjectDownload {

  public static void streamObjectDownload(
      String projectId, String bucketName, String objectName, String targetFile)
      throws IOException {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The ID of your GCS object
    // String objectName = "your-object-name";

    // The path to the file to download the object to
    // String targetFile = "path/to/your/file";
    Path targetFilePath = Paths.get(targetFile);

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    try (ReadChannel reader = storage.reader(BlobId.of(bucketName, objectName));
        FileChannel targetFileChannel =
            FileChannel.open(targetFilePath, StandardOpenOption.WRITE)) {

      ByteStreams.copy(reader, targetFileChannel);

      System.out.println(
          "Downloaded object "
              + objectName
              + " from bucket "
              + bucketName
              + " to "
              + targetFile
              + " using a ReadChannel.");
    }
  }
}

Node.js

詳細については、 Cloud Storage Node.js API リファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The ID of your GCS file
// const fileName = 'your-file-name';

// The filename and file path where you want to download the file
// const destFileName = '/local/path/to/file.txt';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function streamFileDownload() {
  // The example below demonstrates how we can reference a remote file, then
  // pipe its contents to a local file.
  // Once the stream is created, the data can be piped anywhere (process, sdout, etc)
  await storage
    .bucket(bucketName)
    .file(fileName)
    .createReadStream() //stream is created
    .pipe(fs.createWriteStream(destFileName))
    .on('finish', () => {
      // The file download is complete
    });

  console.log(
    `gs://${bucketName}/${fileName} downloaded to ${destFileName}.`
  );
}

streamFileDownload().catch(console.error);

PHP

詳細については、 Cloud Storage PHP API リファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

use Google\Cloud\Storage\StorageClient;

/**
 * Download an object from Cloud Storage and save it as a local file.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 *        (e.g. 'my-object')
 * @param string $destination The local destination to save the object.
 *        (e.g. '/path/to/your/file')
 */
function download_object(string $bucketName, string $objectName, string $destination): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->downloadToFile($destination);
    printf(
        'Downloaded gs://%s/%s to %s' . PHP_EOL,
        $bucketName,
        $objectName,
        basename($destination)
    );
}

Python

詳細については、 Cloud Storage Python API リファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

from google.cloud import storage


def download_blob_to_stream(bucket_name, source_blob_name, file_obj):
    """Downloads a blob to a stream or other file-like object."""

    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"

    # The ID of your GCS object (blob)
    # source_blob_name = "storage-object-name"

    # The stream or file (file-like object) to which the blob will be written
    # import io
    # file_obj = io.BytesIO()

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)

    # Construct a client-side representation of a blob.
    # Note `Bucket.blob` differs from `Bucket.get_blob` in that it doesn't
    # retrieve metadata from Google Cloud Storage. As we don't use metadata in
    # this example, using `Bucket.blob` is preferred here.
    blob = bucket.blob(source_blob_name)
    blob.download_to_file(file_obj)

    print(f"Downloaded blob {source_blob_name} to file-like object.")

    return file_obj
    # Before reading from file_obj, remember to rewind with file_obj.seek(0).

Ruby

詳細については、 Cloud Storage Ruby API リファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

# Downloads a blob to a stream or other file-like object.

# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"

# Name of a file in the Storage bucket
# file_name   = "some_file.txt"

# The stream or file (file-like object) to which the contents will be written
# local_file_obj = StringIO.new

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket  = storage.bucket bucket_name
file    = bucket.file file_name

file.download local_file_obj, verify: :none

# rewind the object before starting to read the downloaded contents
local_file_obj.rewind
puts "The full downloaded file contents are: #{local_file_obj.read.inspect}"

Rust

use google_cloud_storage::client::Storage;

pub async fn sample(client: &Storage, bucket_id: &str) -> anyhow::Result<()> {
    const NAME: &str = "object-to-download.txt";
    let mut reader = client
        .read_object(format!("projects/_/buckets/{bucket_id}"), NAME)
        .send()
        .await?;
    println!("counting newlines {NAME} in bucket {bucket_id}");
    let mut count = 0;
    while let Some(buffer) = reader.next().await.transpose()? {
        count += buffer.into_iter().filter(|c| *c == b'\n').count();
    }
    println!("object {NAME} in bucket {bucket_id} contains {count} newlines");
    Ok(())
}

REST API

JSON API

読み取りのストリーミングを行うには、次の点に注意して、 オブジェクトをダウンロードする手順に沿って操作します。

  • 読み取りを開始する前に、オブジェクトのメタデータを取得して オブジェクトの世代番号を保存します。元のデータが上書きされた場合に、異なる 2 つの世代からデータを読み取らないように、リクエストごとにこの世代番号を含めます。

  • リクエストで Range ヘッダーを使用してオブジェクト全体の一部を取得し、それをローカル プロセスに送信します。

  • オブジェクト全体が取得されるまで、オブジェクトの連続部分に対してリクエストを続行します。

XML API

読み取りのストリーミングを行うには、次の点に注意して、 オブジェクトをダウンロードする手順に沿って操作します。

  • 読み取りを開始する前に、オブジェクトのメタデータを取得して オブジェクトの世代番号を保存します。元のデータが上書きされた場合に、異なる 2 つの世代からデータを読み取らないように、リクエストごとにこの世代番号を含めます。

  • リクエストで Range ヘッダーを使用してオブジェクト全体の一部を取得し、それをローカル プロセスに送信します。

  • オブジェクト全体が取得されるまで、オブジェクトの連続部分に対してリクエストを続行します。

次のステップ