次の方法で共有


Java での Azure Files 用の開発

Azure Files を使用してデータを格納する Java アプリケーションを開発する方法について説明します。 Azure Files は、クラウド内のマネージド ファイル共有サービスです。 業界標準のサーバー メッセージ ブロック (SMB) プロトコルとネットワーク ファイル システム (NFS) プロトコルを介してアクセスできるフル マネージドのファイル共有を提供します。 Azure Files には、ファイル共有へのプログラムによるアクセスのための REST API も用意されています。

この記事では、Java で Azure Files を使用して開発するためのさまざまな方法と、アプリのニーズに最も適したアプローチを選択する方法について説明します。 また、Azure Files リソースと対話する基本的なコンソール アプリを作成する方法についても説明します。

適用対象

管理モデル 課金モデル メディア階層 冗長性 SMB NFS
Microsoft.Storage プロビジョニング済み v2 HDD (標準) ローカル (LRS) はい いいえ
Microsoft.Storage プロビジョニング済み v2 HDD (標準) ゾーン (ZRS) はい いいえ
Microsoft.Storage プロビジョニング済み v2 HDD (標準) ジオ (GRS) はい いいえ
Microsoft.Storage プロビジョニング済み v2 HDD (標準) ジオゾーン (GZRS) はい いいえ
Microsoft.Storage プロビジョニング済み v1 SSD (プレミアム) ローカル (LRS) はい いいえ
Microsoft.Storage プロビジョニング済み v1 SSD (プレミアム) ゾーン (ZRS) はい いいえ
Microsoft.Storage 従量課金制 HDD (標準) ローカル (LRS) はい いいえ
Microsoft.Storage 従量課金制 HDD (標準) ゾーン (ZRS) はい いいえ
Microsoft.Storage 従量課金制 HDD (標準) ジオ (GRS) はい いいえ
Microsoft.Storage 従量課金制 HDD (標準) ジオゾーン (GZRS) はい いいえ

Azure Files を使用した Java アプリ開発について

Azure Files には、Java 開発者が Azure Files のデータにアクセスしてリソースを管理するためのいくつかの方法が用意されています。 次の表に、アプローチの一覧を示し、その動作を要約し、各アプローチを使用するタイミングに関するガイダンスを示します。

方法 動作方法 いつ使用するか
標準ファイル I/O ライブラリ SMB または NFS を使用してマウントされた Azure ファイル共有を介して OS レベルの API 呼び出しを使用します。 SMB/NFS を使用してファイル共有をマウントする場合は、java の java.iojava.nio などのプログラミング言語またはフレームワークにファイル I/O ライブラリを使用できます。 標準ファイル I/O を使用する既存のコードを含む基幹業務アプリがあり、アプリが Azure ファイル共有で動作するようにコードを書き換える必要はありません。
FileREST API HTTPS エンドポイントを直接呼び出して、Azure Files に格納されているデータと対話します。 ファイル共有リソースをプログラムで制御できます。 Azure SDK には、FileREST API 上に構築された File Shares クライアント ライブラリ (com.azure.storage.file.share) が用意されており、使い慣れた Java プログラミング言語パラダイムを使用して FileREST API 操作を操作できます。 お客様向けに付加価値の高いクラウド サービスとアプリを構築しており、標準のファイル I/O ライブラリでは利用できない高度な機能を使用する必要があります。
ストレージ リソース プロバイダー REST API Azure Resource Manager (ARM) を使用して、ストレージ アカウントとファイル共有を管理します。 さまざまなリソース管理操作のために REST API エンドポイントを呼び出します。 アプリまたはサービスは、ストレージ アカウントやファイル共有の作成、削除、更新などのリソース管理タスクを実行する必要があります。

これらの方法の一般的な情報については、「 Azure Files を使用したアプリケーション開発の概要」を参照してください。

この記事では、次の方法を使用して Azure Files リソースを操作することに重点を置いています。

[前提条件]

環境を設定する

この記事では、Maven ビルド ツールを使用してサンプル コードをビルドして実行します。 Gradle などの他のビルド ツールも、Azure SDK for Java と連携します。

Maven を使用して新しいコンソール アプリを作成するか、既存のプロジェクトを開きます。 パッケージをインストールし、必要な import ディレクティブを追加するには、次の手順に従います。

パッケージをインストールする

テキスト エディターで pom.xml ファイルを開きます。 BOM ファイルを含めたり直接依存関係を含めたりして、パッケージをインストールします。

BOM ファイルを含める

azure-sdk-bom を追加して、最新バージョンのライブラリに依存します。 次のスニペットでは、 {bom_version_to_target} プレースホルダーをバージョン番号に置き換えます。 azure-sdk-bom を使用すると、個々の依存関係のバージョンを指定する必要ができなくなります。 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>

依存関係のグループに、次の dependency 要素を追加します。 Azure サービスへのパスワードレス接続には、 Azure ID の依存関係が必要です。 リソース マネージャー成果物は BOM ファイルに含まれていないため、直接依存関係として追加する必要があることに注意してください。

<dependency>
  <groupId>com.azure</groupId>
  <artifactId>azure-storage-file-share</artifactId>
</dependency>
<dependency>
  <groupId>com.azure</groupId>
  <artifactId>azure-identity</artifactId>
</dependency>
<dependency>
  <groupId>com.azure</groupId>
  <artifactId>azure-core-management</artifactId>
</dependency>
<dependency>
  <groupId>com.azure.resourcemanager</groupId>
  <artifactId>azure-resourcemanager</artifactId>
  <version>{package_version_to_target}</version>
</dependency>
<dependency>
  <groupId>com.azure.resourcemanager</groupId>
  <artifactId>azure-resourcemanager-storage</artifactId>
  <version>{package_version_to_target}</version>
</dependency>

直接依存関係を含める

ライブラリの特定のバージョンに依存するには、プロジェクトに直接依存関係を追加します。

<dependency>
  <groupId>com.azure</groupId>
  <artifactId>azure-storage-file-share</artifactId>
  <version>{package_version_to_target}</version>
</dependency>
<dependency>
  <groupId>com.azure</groupId>
  <artifactId>azure-identity</artifactId>
  <version>{package_version_to_target}</version>
</dependency>
<dependency>
  <groupId>com.azure.resourcemanager</groupId>
  <artifactId>azure-resourcemanager</artifactId>
  <version>{package_version_to_target}</version>
</dependency>
<dependency>
  <groupId>com.azure.resourcemanager</groupId>
  <artifactId>azure-resourcemanager-storage</artifactId>
  <version>{package_version_to_target}</version>
</dependency>
<dependency>
  <groupId>com.azure</groupId>
  <artifactId>azure-core-management</artifactId>
  <version>{package_version_to_target}</version>
</dependency>

インポート ディレクティブを含める

次に、コード ファイルを開き、必要な import ディレクティブを追加します。 この例では、 App.java ファイルに次のディレクティブを追加します。

import com.azure.identity.*;
import com.azure.storage.file.share.*;
import com.azure.resourcemanager.*;
import com.azure.resourcemanager.storage.models.*;
import com.azure.core.management.*;
import com.azure.core.management.profile.*;

Java ファイル I/O ライブラリを使用する場合は、次の import ディレクティブも追加する必要があります。

import java.io.*;
import java.nio.file.*;

Java ファイル I/O ライブラリを使用して Azure Files を操作する

Standard ファイル I/O ライブラリは、Azure Files リソースにアクセスして操作する最も一般的な方法です。 SMB または NFS を使用してファイル共有をマウントすると、オペレーティング システムによってローカル ファイル システムの API 要求がリダイレクトされます。 この方法では、 java.iojava.nioなどの標準のファイル I/O ライブラリを使用して、共有内のファイルやディレクトリを操作できます。

アプリで必要な場合は、Java ファイル I/O ライブラリの使用を検討してください。

  • アプリの互換性: Java ファイル I/O ライブラリを既に使用している既存のコードを使用する基幹業務アプリに最適です。 アプリが Azure ファイル共有を操作するためにコードを書き換える必要はありません。
  • 使いやすさ: Java ファイル I/O ライブラリは、開発者によってよく知られており、使いやすいライブラリです。 Azure Files の重要な価値提案は、SMB と NFS を介してネイティブ ファイル システム API を公開することです。

このセクションでは、Java ファイル I/O ライブラリを使用して Azure Files リソースを操作する方法について説明します。

詳細と例については、次のリソースを参照してください。

ファイル共有をマウントする

Java ファイル I/O ライブラリを使用するには、まずファイル共有をマウントする必要があります。 SMB または NFS を使用してファイル共有をマウントする方法のガイダンスについては、次のリソースを参照してください。

この記事では、次のパスを使用して、Windows でマウントされた SMB ファイル共有を参照します。

String fileSharePath = "Z:\\file-share";

例: Java ファイル I/O ライブラリを使用してファイル共有に接続し、ディレクトリを列挙する

次のコード例は、ファイル共有に接続し、共有内のディレクトリを一覧表示する方法を示しています。

import java.io.*;
import java.nio.file.*;

// Add the following code to a new or existing function

String fileSharePath = "Z:\\file-share";

try {
    File directory = new File(fileSharePath);
    File[] dirs = directory.listFiles(File::isDirectory);
            
    if (dirs != null) {
        for (File dir : dirs) {
            System.out.println(dir.getName());
        }
        System.out.println(dirs.length + " directories found.");
    }
} catch (Exception e) {
    System.out.println("Error: " + e.getMessage());
}

例: Java ファイル I/O ライブラリを使用してファイル共有内のファイルに書き込む

次のコード例は、ファイルにテキストを書き込んで追加する方法を示しています。

import java.io.*;
import java.nio.file.*;
import java.util.Arrays;

// Add the following code to a new or existing function

String fileSharePath = "Z:\\file-share";
String fileName = "test.txt";

try {
    String textToWrite = "First line" + System.lineSeparator();
    Path filePath = Paths.get(fileSharePath, fileName);
        
    // Write initial content to file
    Files.write(filePath, textToWrite.getBytes());
    System.out.println("Initial text written to file");
        
    // Append additional lines to the file
    String[] textToAppend = { "Second line", "Third line" };
    Files.write(filePath, 
                Arrays.asList(textToAppend),
                StandardOpenOption.APPEND);
    System.out.println("Additional lines appended to file");
} catch (IOException ex) {
    System.out.println("Error writing to file: " + ex.getMessage());
}

例: Java ファイル I/O ライブラリを使用してファイル共有内のファイルをロックする

ファイル共有をマウントする SMB クライアントは、ファイル システムのロック メカニズムを使用して共有ファイルへのアクセスを管理できます。

次のコード例は、ファイル共有内のファイルをロックする方法を示しています。

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.*;

// Add the following code to a new or existing function

String fileSharePath = "Z:\\file-share";
String fileName = "test.txt";
String filePath = Paths.get(fileSharePath, fileName).toString();

try (
    FileOutputStream fos = new FileOutputStream(filePath);
    FileChannel fileChannel = fos.getChannel()) {

    // Acquire an exclusive lock on this file
    FileLock lock = fileChannel.lock();

    System.out.println("File is locked.");

    // Perform file operations here

    // Release the lock
    lock.release();
    System.out.println("File lock released.");

} catch (Exception e) {
    e.printStackTrace();
}

SMB と FileREST API の両方を使用する場合、FileREST API はファイル ロックの管理に リース を使用し、SMB はオペレーティング システムによって管理されるファイル システム ロックを使用することに注意してください。 SMB と FileREST API の間のファイル ロック操作の管理の詳細については、「 ファイル ロックの管理」を参照してください。

例: Java ファイル I/O ライブラリを使用してファイル ACL を列挙する

次のコード例は、ファイルのアクセス制御リスト (ACL) を列挙する方法を示しています。

import java.nio.file.*;
import java.nio.file.attribute.AclEntry;
import java.nio.file.attribute.AclFileAttributeView;
import java.util.List;

// Add the following code to a new or existing function

String fileSharePath = "Z:\\file-share";
String fileName = "test.txt";
String filePath = Paths.get(fileSharePath, fileName).toString();

try {
    Path path = Paths.get(filePath);

    // Get the ACL view for the file
    AclFileAttributeView aclView = Files.getFileAttributeView(
            path, AclFileAttributeView.class);

    // Get the ACL entries
    List<AclEntry> aclEntries = aclView.getAcl();

    // List all access rules for the file
    for (AclEntry entry : aclEntries) {
        System.out.println("Identity: " + entry.principal().getName());
        System.out.println("Access Control Type: " + entry.type());
        System.out.println("File System Rights: " + entry.permissions());
        System.out.println();
    }

    System.out.println(aclEntries.size() + " ACL entries found.");
} catch (Exception ex) {
    System.out.println("Error: " + ex.getMessage());
}

Java 用ファイル共有クライアント ライブラリを使用して Azure Files を操作する

FileREST API は、Azure Files へのプログラムによるアクセスを提供します。 これにより、HTTPS エンドポイントを呼び出して、ファイル共有、ディレクトリ、ファイルに対する操作を実行できます。 FileREST API は、ネイティブ プロトコルでは使用できない可能性がある高いスケーラビリティと高度な機能のために設計されています。 Azure SDK には、FileREST API 上に構築された Java 用のファイル共有クライアント ライブラリなどのクライアント ライブラリが用意されています。

アプリケーションで次のものが必要な場合は、FileREST API とファイル共有クライアント ライブラリの使用を検討してください。

  • 高度な機能: ネイティブ プロトコルでは使用できない操作と機能にアクセスします。
  • カスタム クラウド統合: Azure Files と直接やり取りする、バックアップ、ウイルス対策、データ管理などのカスタム付加価値サービスを構築します。
  • パフォーマンスの最適化: データ プレーン操作を使用する大規模なシナリオでは、パフォーマンスの利点を活用できます。

FileREST API は、Azure Files をリソースの階層としてモデル化し、 ディレクトリ または ファイル レベルで実行される操作に推奨されます。 ファイル サービスまたはファイル共有レベルで実行される操作には、ストレージ リソース プロバイダー REST API を使用することをお勧めします。

このセクションでは、Java 用ファイル共有クライアント ライブラリを使用して Azure Files リソースを操作する方法について説明します。

詳細と例については、次のリソースを参照してください。

アクセスを承認し、クライアントを作成する

アプリを Azure Files に接続するには、 ShareClient オブジェクトを作成します。 このオブジェクトは、Azure Files リソースを操作するための開始点です。 次のコード例は、さまざまな承認メカニズムを使用して ShareClient オブジェクトを作成する方法を示しています。

Microsoft Entra ID で承認するには、セキュリティ プリンシパルを使用する必要があります。 必要なセキュリティ プリンシパルの種類は、アプリの実行場所によって異なります。 認証シナリオの詳細については、 Java と Azure ID を使用した Azure 認証に関するページを参照してください。

この記事のコード例を使用するには、Azure RBAC 組み込みロール Storage File Data Privileged Contributor をセキュリティ プリンシパルに割り当てます。 このロールは、設定されているファイル/ディレクトリ レベルの NTFS アクセス許可に関係なく、構成されているすべてのストレージ アカウントの共有内のすべてのデータに対する完全な読み取り、書き込み、ACL の変更、および削除アクセスを提供します。 詳細については、「 Rest 経由の Azure Files OAuth で Microsoft Entra ID を使用して Azure ファイル共有にアクセスする」を参照してください。

DefaultAzureCredential を使用してアクセスを承認する

Azure Files へのアクセスを承認して接続するための簡単で安全な方法は、 DefaultAzureCredential インスタンスを作成して OAuth トークンを取得することです。 その後、その資格情報を使用して、 ShareClient オブジェクトを作成できます。

次の例では、ShareClient を使用して承認されたDefaultAzureCredential オブジェクトを作成し、共有内のディレクトリを操作するShareDirectoryClient オブジェクトを作成します。

import com.azure.core.credential.TokenCredential;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.storage.file.share.*;

// Add the following code to a new or existing function

String accountName = "<account-name>";
String shareName = "<share-name>";
TokenCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build();

// Create the ShareClient
ShareClient shareClient = new ShareClientBuilder()
    .endpoint(String.format("https://%s.file.core.windows.net", accountName))
    .shareName(shareName)
    .credential(defaultAzureCredential)
    .buildClient();

// Create a client to interact with a directory in the share
ShareDirectoryClient directoryClient = shareClient.getDirectoryClient("sample-directory");

ユーザーの認証に使用する資格情報の種類が正確にわかっている場合は、 Java 用 Azure Identity クライアント ライブラリの他のクラスを使用して OAuth トークンを取得できます。 これらのクラスは 、TokenCredential クラスから派生します。

これらの各承認メカニズムの詳細については、「 ファイル データへのアクセスを承認する方法を選択する」を参照してください。

例: ファイル共有クライアント ライブラリを使用してファイルをコピーする

次の方法を使用して、ファイル共有内またはファイル共有間でファイルをコピーできます。

BlockBlobClient オブジェクトから次のメソッドを使用して、ファイルをコピー先 BLOB にコピーできます。

次のコード例は、ファイルを別のファイル共有内のファイルにコピーする方法を示しています。

import java.time.*;
import java.util.*;

import com.azure.core.credential.TokenCredential;
import com.azure.core.util.polling.*;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.storage.file.share.*;
import com.azure.storage.file.share.models.*;

// Add the following code to a new or existing function

String accountName = "<account-name>";
String srcShareName = "src-file-share";
String destShareName = "dest-file-share";
String srcFilePath = "src/path/to/file";
String destFilePath = "dest/path/to/file";

TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();

ShareFileClient srcShareFileClient = new ShareFileClientBuilder()
    .endpoint(String.format("https://%s.file.core.windows.net", accountName))
    .shareName(srcShareName)
    .shareTokenIntent(ShareTokenIntent.BACKUP)
    .resourcePath(srcFilePath)
    .credential(defaultAzureCredential)
    .buildFileClient();

ShareFileClient destShareFileClient = new ShareFileClientBuilder()
    .endpoint(String.format("https://%s.file.core.windows.net", accountName))
    .shareName(destShareName)
    .shareTokenIntent(ShareTokenIntent.BACKUP)
    .resourcePath(destFilePath)
    .credential(defaultAzureCredential)
    .buildFileClient();

// Copy the file from the source share to the destination share
SyncPoller<ShareFileCopyInfo, Void> poller = destShareFileClient
        .beginCopy(srcShareFileClient.getFileUrl(),
                Collections.singletonMap("file", "metadata"),
                Duration.ofSeconds(2));

final PollResponse<ShareFileCopyInfo> pollResponse = poller.poll();
final ShareFileCopyInfo value = pollResponse.getValue();
System.out.printf("Copy source: %s. Status: %s.%n", value.getCopySourceUrl(), value.getCopyStatus());

例: ファイル共有クライアント ライブラリを使用してファイルをリースする

リースは、リース ID を介して Azure によって管理されるファイルに対するロックを作成します。 リースは、分散システム内の複数のクライアント間でファイルへのアクセスを調整するメカニズムを提供します。 ファイルのリースは、排他的な書き込みと削除のアクセスを提供します。 リースの状態とアクションの詳細については、「 リース ファイル」を参照してください。

次のコード例は、リース クライアントを作成し、ファイルで無限期間のリースを取得し、リースを解放する方法を示しています。

import com.azure.core.credential.TokenCredential;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.storage.file.share.*;
import com.azure.storage.file.share.models.*;
import com.azure.storage.file.share.specialized.*;

// Add the following code to a new or existing function

String accountName = "<account-name>";
String shareName = "sample-file-share";
String filePath = "path/to/file";
        
TokenCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build();

ShareFileClient fileClient = new ShareFileClientBuilder()
    .endpoint(String.format("https://%s.file.core.windows.net", accountName))
    .shareName(shareName)
    .shareTokenIntent(ShareTokenIntent.BACKUP)
    .resourcePath(filePath)
    .credential(defaultAzureCredential)
    .buildFileClient();

// Get a ShareLeaseClient
ShareLeaseClient fileLeaseClient = new ShareLeaseClientBuilder()
        .fileClient(fileClient)
        .shareTokenIntent(ShareTokenIntent.BACKUP)
        .buildClient();
        
try {
    // Acquire a lease on the file with infinite duration
    fileLeaseClient.acquireLease();
    System.out.println("Lease acquired successfully");
            
    // Do something with the file

} catch (Exception e) {
    System.err.println("Error: " + e.getMessage());
} finally {
    // Release the lease when finished
    try {
        fileLeaseClient.releaseLease();
        System.out.println("Lease released successfully.");
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
}

SMB と FileREST API の両方を使用する場合、FileREST API はファイル ロックの管理に リース を使用し、SMB はオペレーティング システムによって管理されるファイル システム ロックを使用することに注意してください。 SMB と FileREST API の間のファイル ロック操作の管理の詳細については、「 ファイル ロックの管理」を参照してください。

例: ファイル共有クライアント ライブラリを使用して共有スナップショットを作成および一覧表示する

共有スナップショットは、ある時点でのファイル共有の読み取り専用コピーです。 ファイル共有のスナップショットを作成し、スナップショットを使用して、スナップショットの作成時に共有内のデータにアクセスできます。 ファイル共有内のすべてのスナップショットを一覧表示したり、共有スナップショットを削除したりすることもできます。

次のコード例は、共有スナップショットの作成、ファイル共有内のスナップショットの一覧表示、および共有スナップショット内のディレクトリ ツリーの走査を行う方法を示しています。

import com.azure.storage.file.share.*;
import com.azure.storage.file.share.models.*;

// Add the following code to a new or existing function

public static void main(String[] args) {
    String connectionString = "<connection-string>";

    // Create a ShareServiceClient from which you can create clients for specific shares
    ShareServiceClient shareServiceClient = new ShareServiceClientBuilder()
    .connectionString(connectionString)
        .buildClient();
        
    // Get a client for a specific share
    ShareClient shareClient = shareServiceClient.getShareClient("sample-file-share");

    try {
        // Create a snapshot
        ShareSnapshotInfo snapshotInfo = shareClient.createSnapshot();
        System.out.println("Snapshot created: " + snapshotInfo.getSnapshot());

        // List snapshots in a share
        ListSharesOptions options = new ListSharesOptions()
            .setIncludeSnapshots(true);
                
        for (ShareItem shareItem : shareServiceClient.listShares(options, null, null)) {
            if (shareItem.getSnapshot() != null) {
                System.out.println("Share: " + shareItem.getName() + 
                    " (Snapshot: " + shareItem.getSnapshot() + ")");
            }
        }

        // List directories and files in a share snapshot
        String snapshotTimestamp = snapshotInfo.getSnapshot();
        ShareClient shareSnapshot = shareClient.getSnapshotClient(snapshotTimestamp);
        ShareDirectoryClient rootDir = shareSnapshot.getRootDirectoryClient();

        listDirectoryTree(rootDir);
            
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
    }
 }
    
private static void listDirectoryTree(ShareDirectoryClient directory) {
    // List all files and directories in current directory
    for (ShareFileItem fileItem : directory.listFilesAndDirectories()) {
        if (fileItem.isDirectory()) {
            System.out.println("Directory: " + fileItem.getName());
            // Recursively list subdirectory contents
            listDirectoryTree(directory.getSubdirectoryClient(fileItem.getName()));
        } else {
            System.out.println("File: " + fileItem.getName());
        }
    }
}

DefaultAzureCredentialの使用時に取得した OAuth トークンは、ファイル共有レベルでのデータ プレーン操作には許可されません。 共有スナップショットを操作するには、アカウント キーを使用してクライアント オブジェクトを承認する必要があります。 このコード例で作成した ShareClient オブジェクトは、アカウント キーを含む接続文字列を使用します。

アカウント キーまたは接続文字列を格納すると、セキュリティ上のリスクが伴います。 Microsoft Entra 認証が利用できない場合にのみ使用してください。 Azure Key Vault にアカウント キーを安全に格納する方法の詳細については、「 Azure Key Vault マネージド ストレージ アカウント キーについて」を参照してください。

Azure Storage 管理ライブラリを使用して Azure Files リソースを管理する

Azure Storage 管理ライブラリは、Azure Storage リソース プロバイダー REST API 上に構築されています。 Azure Storage リソース プロバイダーは 、Azure Resource Manager に基づくサービスであり、宣言型 (テンプレート) メソッドと命令型 (直接 API 呼び出し) メソッドの両方をサポートします。 Azure Storage リソース プロバイダー REST API は、ファイル共有を含む Azure Storage リソースへのプログラムによるアクセスを提供します。 Azure SDK には、Azure Storage リソース プロバイダー REST API 上に構築された管理ライブラリが用意されています。

管理ライブラリは、 ファイル サービス または ファイル共有 レベルで実行される操作に推奨されます。 このセクションでは、Azure Storage 管理ライブラリを使用して Azure Files リソースを管理する方法について説明します。

Azure Storage 管理ライブラリは、Azure Storage リソース プロバイダー REST API 上に構築されています。 Azure Storage リソース プロバイダーは 、Azure Resource Manager に基づくサービスであり、宣言型 (テンプレート) メソッドと命令型 (直接 API 呼び出し) メソッドの両方をサポートします。 Azure Storage リソース プロバイダー REST API は、ファイル共有を含む Azure Storage リソースへのプログラムによるアクセスを提供します。 Azure SDK には、Azure Storage リソース プロバイダー REST API 上に構築された管理ライブラリが用意されています。

管理ライブラリは、 ファイル サービス または ファイル共有 レベルで実行される操作に推奨されます。 このセクションでは、Azure Storage 管理ライブラリを使用して Azure Files リソースを管理する方法について説明します。

例: Azure Storage 管理ライブラリを使用してファイル共有を作成する

次のコード例は、最上位の AzureResourceManager オブジェクトを作成し、ストレージ リソース プロバイダーをサブスクリプションに登録し、Azure Storage 管理ライブラリを使用してファイル共有を作成する方法を示しています。

import com.azure.identity.*;
import com.azure.resourcemanager.*;
import com.azure.resourcemanager.storage.fluent.*;
import com.azure.resourcemanager.storage.fluent.models.*;

import com.azure.core.credential.TokenCredential;
import com.azure.core.management.*;
import com.azure.core.management.profile.*;

// Add the following code to a new or existing function

String subscriptionID = "<subscription-id>";
String rgName = "<resource-group-name>";
String saName = "<storage-account-name>";
TokenCredential credential = new DefaultAzureCredentialBuilder().build();
AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);

AzureResourceManager armClient = AzureResourceManager
        .configure()
        .authenticate(credential, profile)
        .withSubscription(subscriptionID);

// Check the registration state of the resource provider and register, if needed
if (armClient.providers().getByName("Microsoft.Storage").registrationState() == "NotRegistered")
    armClient.providers().register("Microsoft.Storage");

// Create a new file share

StorageManagementClient storageManagementClient = armClient.storageAccounts().manager().serviceClient();
FileSharesClient fileShare = storageManagementClient.getFileShares();

String shareName = "sample-file-share";
int quotaInGB = 1;
        
// Create the file share
fileShare.create(
    rgName,
    saName,
    shareName,
    new FileShareInner()
        .withShareQuota(quotaInGB)
);

FileShareInner クラスを使用して、ファイル共有プロパティを構成できます。 前の例は、ファイル共有を作成するときに共有クォータを設定する方法を示しています。 既存のファイル共有を更新するには、 fileShare.update() を呼び出し、更新するプロパティを使用して FileShareInner オブジェクトを渡します。

登録操作を実行するには、次の Azure RBAC アクション (Microsoft.Storage/register/action) のアクセス許可が必要です。 このアクセス許可は、寄稿者ロールと所有者標準ロールに含まれています。

例: Azure Storage 管理ライブラリを使用してファイル共有とスナップショットを一覧表示する

次のコード例は、ストレージ アカウント内のファイル共有とスナップショットを一覧表示する方法を示しています。

import com.azure.identity.*;
import com.azure.resourcemanager.*;
import com.azure.resourcemanager.storage.fluent.*;
import com.azure.resourcemanager.storage.fluent.models.*;

import com.azure.core.credential.TokenCredential;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.management.*;
import com.azure.core.management.profile.*;
import com.azure.core.util.Context;

// Add the following code to a new or existing function

String subscriptionID = "<subscription-id>";
String rgName = "<resource-group-name>";
String saName = "<storage-account-name>";
TokenCredential credential = new DefaultAzureCredentialBuilder().build();
AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);

AzureResourceManager armClient = AzureResourceManager
        .configure()
        .authenticate(credential, profile)
        .withSubscription(subscriptionID);

// Check the registration state of the resource provider and register, if needed
if (armClient.providers().getByName("Microsoft.Storage").registrationState() == "NotRegistered")
    armClient.providers().register("Microsoft.Storage");

StorageManagementClient storageManagementClient = armClient.storageAccounts().manager().serviceClient();
FileSharesClient fileShare = storageManagementClient.getFileShares();

// List all file shares and include snapshots

PagedIterable<FileShareItemInner> fileShares = fileShare.list(
    rgName,               // resource group name
    saName,               // storage account name
    null,                 // maxpagesize
    null,                 // filter
    "snapshots",          // expand to include snapshots
    Context.NONE);        // context

for (FileShareItemInner fileShareItem : fileShares) {
    System.out.println("File share name: " + fileShareItem.name());
    System.out.println("File share quota: " + fileShareItem.shareQuota());
}

次のステップ

Azure Files を使用した開発の詳細については、次のリソースを参照してください。