Java 用 Azure Storage BLOB クライアント ライブラリ - バージョン 12.24.1

Azure Blob Storage は、Microsoft のクラウド用オブジェクト ストレージ ソリューションです。 Blob Storage は、テキスト データやバイナリ データなどの大量の非構造化データを格納するために最適化されています。 非構造化データとは、特定のデータ モデルや定義に従っていないデータであり、テキスト データやバイナリ データなどがあります。

ソースコード | API リファレンス ドキュメント | REST API のドキュメント | 製品ドキュメント | サンプル

作業の開始

前提条件

パッケージを組み込む

BOM ファイルを含める

GA バージョンのライブラリに依存するには、azure-sdk-bom をプロジェクトに含めてください。 次のスニペットでは、{bom_version_to_target} プレースホルダーをバージョン番号に置き換えます。 BOM の詳細については、 AZURE SDK BOM README に関するページを参照してください。

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-sdk-bom</artifactId>
            <version>{bom_version_to_target}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

次に、バージョン タグのない依存関係セクションに直接依存関係を含めます。

<dependencies>
  <dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-storage-blob</artifactId>
  </dependency>
</dependencies>

直接依存関係を含める

BOM に存在しない特定のバージョンのライブラリに依存する場合は、次のように直接依存関係をプロジェクトに追加します。

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-storage-blob</artifactId>
    <version>12.24.1</version>
</dependency>

ストレージ アカウントを作成する

ストレージ アカウントを作成するには、 Azure Portal または Azure CLI を使用できます。

az storage account create \
    --resource-group <resource-group-name> \
    --name <storage-account-name> \
    --location <location>

ストレージ アカウントの URL (後で として <your-storage-account-url>識別されます) は、次のように書式設定されます。 http(s)://<storage-account-name>.blob.core.windows.net

クライアントを認証する

ストレージ サービス (Blob、Queue、Message、MessageId、File) と対話するには、Service Client クラスのインスタンスを作成する必要があります。 これを可能にするには、ストレージ アカウントのアカウント SAS (共有アクセス署名) 文字列が必要です。 詳細については、 SAS トークンに関するページを参照してください。

資格情報の取得

SAS トークン

a. 次の Azure CLI スニペットを使用して、ストレージ アカウントから SAS トークンを取得します。

az storage blob generate-sas \
    --account-name {Storage Account name} \
    --container-name {container name} \
    --name {blob name} \
    --permissions {permissions to grant} \
    --expiry {datetime to expire the SAS token} \
    --services {storage services the SAS allows} \
    --resource-types {resource types the SAS allows}

例:

CONNECTION_STRING=<connection-string>

az storage blob generate-sas \
    --account-name MyStorageAccount \
    --container-name MyContainer \
    --name MyBlob \
    --permissions racdw \
    --expiry 2020-06-15

b. または、Azure Portal からアカウント SAS トークンを取得します。

  1. ストレージ アカウントに移動する
  2. 左側のメニューから選択 Shared access signature します
  3. (セットアップ後) をクリックしますGenerate SAS and connection string
共有キーの資格情報

a. [アカウント名] と [アカウント キー] を使用します。 アカウント名はストレージ アカウント名です。

  1. ストレージ アカウントに移動する
  2. 左側のメニューから選択 Access keys します
  3. [copy the contents of the field]\(フィールドの内容をコピーする\) の下key1/key2Key

または

b. 接続文字列を使用します。

  1. ストレージ アカウントに移動する
  2. 左側のメニューから選択 Access keys します
  3. [copy the contents of the field]\(フィールドの内容をコピーする\) の下key1/key2Connection string

主要な概念

Blob Storage は、次の目的で設計されています。

  • 画像またはドキュメントをブラウザーに直接配信する
  • 分散アクセス用のファイルの格納
  • ビデオやオーディオのストリーミング
  • ログ ファイルへの書き込み
  • バックアップと復元、ディザスター リカバリー、アーカイブのためのデータの格納
  • オンプレミス サービスまたは Azure ホステッド サービスによる分析のためのデータの格納

URL 形式

BLOB は、次の URL 形式を使用してアドレス指定できます。次の URL は BLOB をアドレス指定します。

https://myaccount.blob.core.windows.net/mycontainer/myblob

リソースの URI の構文

ストレージ アカウントの場合、BLOB 操作のベース URI にはアカウントの名前のみが含まれます。

https://myaccount.blob.core.windows.net

コンテナーの場合、キュー操作のベース URI にはアカウントの名前とコンテナーの名前が含まれます。

https://myaccount.blob.core.windows.net/mycontainer

BLOB の場合、ベース URI には、アカウントの名前、コンテナーの名前、BLOB の名前が含まれます。

https://myaccount.blob.core.windows.net/mycontainer/myblob

上記の URI は、カスタム ドメイン名などのより高度なシナリオでは保持されない場合があることに注意してください。

次のセクションでは、次のような最も一般的な Azure Storage BLOB タスクをカバーするいくつかのコード スニペットを示します。

認証要求の処理に使用する BlobServiceClient

上記で BlobServiceClient 生成した を使用して を sasToken 作成します。

BlobServiceClient blobServiceClient = new BlobServiceClientBuilder()
    .endpoint("<your-storage-account-url>")
    .sasToken("<your-sasToken>")
    .buildClient();

または

// Only one "?" is needed here. If the SAS token starts with "?", please removing one "?".
BlobServiceClient blobServiceClient = new BlobServiceClientBuilder()
    .endpoint("<your-storage-account-url>" + "?" + "<your-sasToken>")
    .buildClient();

認証要求の処理に使用する BlobContainerClient

を使用して を BlobContainerClient 作成します BlobServiceClient

BlobContainerClient blobContainerClient = blobServiceClient.getBlobContainerClient("mycontainer");

上で BlobContainerClient 生成したビルダーから を作成します sasToken

BlobContainerClient blobContainerClient = new BlobContainerClientBuilder()
    .endpoint("<your-storage-account-url>")
    .sasToken("<your-sasToken>")
    .containerName("mycontainer")
    .buildClient();

または

// Only one "?" is needed here. If the SAS token starts with "?", please removing one "?".
BlobContainerClient blobContainerClient = new BlobContainerClientBuilder()
    .endpoint("<your-storage-account-url>" + "/" + "mycontainer" + "?" + "<your-sasToken>")
    .buildClient();

認証要求の処理に使用する BlobClient

を使用して を BlobClient 作成します BlobContainerClient

BlobClient blobClient = blobContainerClient.getBlobClient("myblob");

または

上で BlobClient 生成したビルダーから を作成します sasToken

BlobClient blobClient = new BlobClientBuilder()
    .endpoint("<your-storage-account-url>")
    .sasToken("<your-sasToken>")
    .containerName("mycontainer")
    .blobName("myblob")
    .buildClient();

または

// Only one "?" is needed here. If the SAS token starts with "?", please removing one "?".
BlobClient blobClient = new BlobClientBuilder()
    .endpoint("<your-storage-account-url>" + "/" + "mycontainer" + "/" + "myblob" + "?" + "<your-sasToken>")
    .buildClient();

コンテナーを作成する

を使用してコンテナーを BlobServiceClient作成します。

blobServiceClient.createBlobContainer("mycontainer");

または

を使用してコンテナーを BlobContainerClient作成します。

blobContainerClient.create();

BLOB にデータをアップロードする

から生成された を使用して BlobClient BLOB にアップロードBinaryDataしますBlobContainerClient

BlobClient blobClient = blobContainerClient.getBlobClient("myblockblob");
String dataSample = "samples";
blobClient.upload(BinaryData.fromString(dataSample));

ストリームから BLOB をアップロードする

から生成された を InputStream 使用して、 BlockBlobClient から BLOB にアップロードします BlobContainerClient

BlockBlobClient blockBlobClient = blobContainerClient.getBlobClient("myblockblob").getBlockBlobClient();
String dataSample = "samples";
try (ByteArrayInputStream dataStream = new ByteArrayInputStream(dataSample.getBytes())) {
    blockBlobClient.upload(dataStream, dataSample.length());
} catch (IOException e) {
    e.printStackTrace();
}

ローカル パスから BLOB をアップロードする

から生成された を使用して BlobClient 、BLOB にファイルを BlobContainerClientアップロードします。

BlobClient blobClient = blobContainerClient.getBlobClient("myblockblob");
blobClient.uploadFromFile("local-file.jpg");

BLOB がまだ存在しない場合はアップロードする

BLOB にデータをアップロードし、既に存在する場合は失敗します。

/*
 * Rather than use an if block conditioned on an exists call, there are three ways to upload-if-not-exists using
 * one network call instead of two. Equivalent options are present on all upload methods.
 */
// 1. The minimal upload method defaults to no overwriting
String dataSample = "samples";
try (ByteArrayInputStream dataStream = new ByteArrayInputStream(dataSample.getBytes())) {
    blobClient.upload(dataStream, dataSample.length());
} catch (IOException e) {
    e.printStackTrace();
}

// 2. The overwrite flag can explicitly be set to false to make intention clear
try (ByteArrayInputStream dataStream = new ByteArrayInputStream(dataSample.getBytes())) {
    blobClient.upload(dataStream, dataSample.length(), false /* overwrite */);
} catch (IOException e) {
    e.printStackTrace();
}

// 3. If the max overload is needed, access conditions must be used to prevent overwriting
try (ByteArrayInputStream dataStream = new ByteArrayInputStream(dataSample.getBytes())) {
    BlobParallelUploadOptions options =
        new BlobParallelUploadOptions(dataStream, dataSample.length());
    // Setting IfNoneMatch="*" ensures the upload will fail if there is already a blob at the destination.
    options.setRequestConditions(new BlobRequestConditions().setIfNoneMatch("*"));
    blobClient.uploadWithResponse(options, null, Context.NONE);
} catch (IOException e) {
    e.printStackTrace();
}

BLOB をアップロードし、既に存在する場合は上書きする

BLOB にデータをアップロードし、コピー先の既存のデータを上書きします。

/*
 * Rather than use an if block conditioned on an exists call, there are three ways to upload-if-exists in one
 * network call instead of two. Equivalent options are present on all upload methods.
 */
String dataSample = "samples";

// 1. The overwrite flag can explicitly be set to true. This will succeed as a create and overwrite.
try (ByteArrayInputStream dataStream = new ByteArrayInputStream(dataSample.getBytes())) {
    blobClient.upload(dataStream, dataSample.length(), true /* overwrite */);
} catch (IOException e) {
    e.printStackTrace();
}

/*
 * 2. If the max overload is needed and no access conditions are passed, the upload will succeed as both a
 * create and overwrite.
 */
try (ByteArrayInputStream dataStream = new ByteArrayInputStream(dataSample.getBytes())) {
    BlobParallelUploadOptions options =
        new BlobParallelUploadOptions(dataStream, dataSample.length());
    blobClient.uploadWithResponse(options, null, Context.NONE);
} catch (IOException e) {
    e.printStackTrace();
}

/*
 * 3. If the max overload is needed, access conditions may be used to assert that the upload is an overwrite and
 * not simply a create.
 */
try (ByteArrayInputStream dataStream = new ByteArrayInputStream(dataSample.getBytes())) {
    BlobParallelUploadOptions options =
        new BlobParallelUploadOptions(dataStream, dataSample.length());
    // Setting IfMatch="*" ensures the upload will succeed only if there is already a blob at the destination.
    options.setRequestConditions(new BlobRequestConditions().setIfMatch("*"));
    blobClient.uploadWithResponse(options, null, Context.NONE);
} catch (IOException e) {
    e.printStackTrace();
}

を使用して BLOB をアップロードする OutputStream

を開 BlobOutputStream き、標準ストリーム API を介して書き込んで BLOB をアップロードします。

/*
 * Opening a blob input stream allows you to write to a blob through a normal stream interface. It will not be
 * committed until the stream is closed.
 * This option is convenient when the length of the data is unknown.
 * This can only be done for block blobs. If the target blob already exists as another type of blob, it will
 * fail.
 */
try (BlobOutputStream blobOS = blobClient.getBlockBlobClient().getBlobOutputStream()) {
    blobOS.write(new byte[0]);
} catch (IOException e) {
    e.printStackTrace();
}

BLOB からデータをダウンロードする

を使用して BLOB を に OutputStream ダウンロードします BlobClient

BinaryData content = blobClient.downloadContent();

BLOB をストリームにダウンロードする

を使用して BLOB を に OutputStream ダウンロードします BlobClient

try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
    blobClient.downloadStream(outputStream);
} catch (IOException e) {
    e.printStackTrace();
}

BLOB をローカル パスにダウンロードする

を使用して BLOB をローカル ファイルにダウンロードします BlobClient

blobClient.downloadToFile("downloaded-file.jpg");

を使用して BLOB を読み取る InputStream

を開 BlobInputStream き、標準ストリーム API から読み取って BLOB をダウンロードします。

/*
 * Opening a blob input stream allows you to read from a blob through a normal stream interface. It is also
 * mark-able.
*/
try (BlobInputStream blobIS = blobClient.openInputStream()) {
    blobIS.read();
} catch (IOException e) {
    e.printStackTrace();
}

BLOB を列挙する

を使用して BlobContainerClientすべての BLOB を列挙します。

for (BlobItem blobItem : blobContainerClient.listBlobs()) {
    System.out.println("This is the blob name: " + blobItem.getName());
}

または

すべての BLOB を列挙し、項目を指す新しいクライアントを作成します。

for (BlobItem blobItem : blobContainerClient.listBlobs()) {
    BlobClient blobClient;
    if (blobItem.getSnapshot() != null) {
        blobClient = blobContainerClient.getBlobClient(blobItem.getName(), blobItem.getSnapshot());
    } else {
        blobClient = blobContainerClient.getBlobClient(blobItem.getName());
    }
    System.out.println("This is the new blob uri: " + blobClient.getBlobUrl());
}

BLOB をコピーする

BLOB のコピー。 コピー ソースとその認証に関する要件の詳細については、これらの各方法の javadocs を参照してください。

SyncPoller<BlobCopyInfo, Void> poller = blobClient.beginCopy("<url-to-blob>", Duration.ofSeconds(1));
poller.waitForCompletion();

または

blobClient.copyFromUrl("url-to-blob");

SAS トークンを生成する

クライアントのインスタンスを使用して、新しい SAS トークンを生成します。

/*
 * Generate an account sas. Other samples in this file will demonstrate how to create a client with the sas
 * token.
 */
// Configure the sas parameters. This is the minimal set.
OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1);
AccountSasPermission accountSasPermission = new AccountSasPermission().setReadPermission(true);
AccountSasService services = new AccountSasService().setBlobAccess(true);
AccountSasResourceType resourceTypes = new AccountSasResourceType().setObject(true);

// Generate the account sas.
AccountSasSignatureValues accountSasValues =
    new AccountSasSignatureValues(expiryTime, accountSasPermission, services, resourceTypes);
String sasToken = blobServiceClient.generateAccountSas(accountSasValues);

// Generate a sas using a container client
BlobContainerSasPermission containerSasPermission = new BlobContainerSasPermission().setCreatePermission(true);
BlobServiceSasSignatureValues serviceSasValues =
    new BlobServiceSasSignatureValues(expiryTime, containerSasPermission);
blobContainerClient.generateSas(serviceSasValues);

// Generate a sas using a blob client
BlobSasPermission blobSasPermission = new BlobSasPermission().setReadPermission(true);
serviceSasValues = new BlobServiceSasSignatureValues(expiryTime, blobSasPermission);
blobClient.generateSas(serviceSasValues);

Azure Identity を使用して認証する

Azure Identity ライブラリは、Azure Storage を使用した認証のための Azure Active Directory サポートを提供します。

BlobServiceClient blobStorageClient = new BlobServiceClientBuilder()
    .endpoint("<your-storage-account-url>")
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildClient();

クライアントのビルド時にプロキシを設定する

ProxyOptions options = new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("localhost", 888));
BlobServiceClient client = new BlobServiceClientBuilder()
    .httpClient(new NettyAsyncHttpClientBuilder().proxy(options).build())
    .buildClient();

または

クライアント ビルダーが使用する型を HttpClient 決定し、渡された構成で構築できるようにします。

HttpClientOptions clientOptions = new HttpClientOptions()
    .setProxyOptions(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("localhost", 888)));
BlobServiceClient client = new BlobServiceClientBuilder()
    .clientOptions(clientOptions)
    .buildClient();

トラブルシューティング

この Java クライアント ライブラリを使用して BLOB を操作する場合、サービスによって返されるエラーは、 REST API 要求に対して返されるのと同じ HTTP 状態コードに対応します。 たとえば、ストレージ アカウントに存在しないコンテナーまたは BLOB を取得しようとすると、 404 を示す Not Foundエラーが返されます。

既定の HTTP クライアント

すべてのクライアント ライブラリでは、Netty HTTP クライアントが既定で使用されます。 前述の依存関係を追加すると、Netty HTTP クライアントを使用するようにクライアント ライブラリが自動的に構成されます。 HTTP クライアントの構成と変更については、HTTP クライアントの Wiki で詳しく説明されています。

既定の SSL ライブラリ

すべてのクライアント ライブラリは、Tomcat ネイティブの Boring SSL ライブラリを既定で使用して、SSL 操作にネイティブレベルのパフォーマンスを実現しています。 Boring SSL ライブラリは、Linux、macOS、Windows のネイティブ ライブラリを含んだ uber jar であり、JDK 内の既定の SSL 実装よりも優れたパフォーマンスを備えています。 依存関係のサイズを縮小する方法など、詳細については、Wiki の「パフォーマンス チューニング」セクションを参照してください。

次の手順

SDK の GitHub リポジトリでは、いくつかのストレージ BLOB Java SDK サンプルを使用できます。 これらのサンプルでは、Key Vaultの操作中に一般的に発生するその他のシナリオのコード例を示します。

次の手順のサンプル

サンプルについては、 こちらを参照してください

共同作成

このプロジェクトでは、共同作成と提案を歓迎しています。 ほとんどの共同作成では、共同作成者使用許諾契約書 (CLA) にご同意いただき、ご自身の共同作成内容を使用する権利を Microsoft に供与する権利をお持ちであり、かつ実際に供与することを宣言していただく必要があります。

pull request を送信すると、CLA を提供して PR (ラベル、コメントなど) を適宜装飾する必要があるかどうかを CLA ボットが自動的に決定します。 ボットによって提供される手順にそのまま従ってください。 この操作は、Microsoft の CLA を使用するすべてのリポジトリについて、1 回だけ行う必要があります。

このプロジェクトでは、Microsoft オープン ソースの倫理規定を採用しています。 詳しくは、「Code of Conduct FAQ (倫理規定についてよくある質問)」を参照するか、opencode@microsoft.com 宛てに質問またはコメントをお送りください。

インプレッション数