瞭解如何開發使用 Azure 檔案儲存體來儲存資料的 Java 應用程式。 Azure 檔案儲存體是雲端中的受控檔案共用服務。 它提供完全託管的檔案共用,可透過業界標準伺服器訊息區塊 (SMB) 和網路檔案系統 (NFS) 協定存取。 Azure 檔案儲存體也提供 REST API,以程序化存取檔案共用。
在本文中,您將瞭解使用 Java 中的 Azure 檔案儲存體進行開發的不同方法,以及如何選擇最適合應用程式需求的方法。 您也會瞭解如何建立與 Azure 檔案儲存體資源互動的基本主控台應用程式。
適用於
| 管理模型 | 計費模型 | 媒體分層 | Redundancy | SMB | NFS |
|---|---|---|---|---|---|
| Microsoft.Storage | 已佈建的 v2 | HDD (標準) | 本地 (LRS) |
|
|
| Microsoft.Storage | 已佈建的 v2 | HDD (標準) | 區域 (ZRS) |
|
|
| Microsoft.Storage | 已佈建的 v2 | HDD (標準) | 異地 (GRS) |
|
|
| Microsoft.Storage | 已佈建的 v2 | HDD (標準) | GeoZone (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 (標準) | GeoZone (GZRS) |
|
|
關於使用 Azure 檔案儲存體進行 Java 應用程式開發
Azure 檔案儲存體提供數種方式讓 Java 開發人員存取資料並管理 Azure 檔案儲存體中的資源。 下表列出這些方法、摘要說明其運作方式,並提供使用每個方法時機的指引:
| 方法 | 運作方式 | 使用時機 |
|---|---|---|
| 標準檔案輸入/輸出函式庫 | 透過使用 SMB 或 NFS 掛載的 Azure 檔案共用使用作業系統層級的 API 呼叫。 當您使用 SMB/NFS 挂載檔案共用時,可以在程式設計語言(如 Java)或框架中使用檔案 I/O 程式庫,例如 java.io 和 java.nio。 |
您有具有使用標準檔案 I/O 之現有程式代碼的企業營運應用程式,而且您不想要重寫程式代碼,讓應用程式使用 Azure 檔案共用。 |
| FileREST API | 直接呼叫 HTTPS 端點,以與儲存在 Azure 檔案服務中的數據互動。 提供檔案共用資源的程序設計控制。 Azure SDK 提供以 FileREST API 為基礎的檔案共用用戶端程式庫 (com.azure.storage.file.share),可讓您透過熟悉的 Java 程式設計語言範例與 FileREST API 作業互動。 |
您正在為客戶建置加值雲端服務和應用程式,並且想要使用標準檔案 I/O 程式庫無法提供的進階功能。 |
| 記憶體資源提供者 REST API | 使用 Azure Resource Manager (ARM) 來管理記憶體帳戶和檔案共用。 針對各種資源管理作業呼叫 REST API 端點。 | 您的應用程式或服務必須執行資源管理工作,例如建立、刪除或更新記憶體帳戶或檔案共用。 |
如需這些方法的一般資訊,請參閱使用 Azure 檔案儲存體進行應用程式開發概觀。
本文著重於使用下列方法來使用 Azure 檔案儲存體資源:
- 使用 Java 檔案 I/O 程式庫操作 Azure 檔案分享:透過 SMB 或 NFS 掛載檔案分享,並使用 Java 檔案 I/O 程式庫來處理分享中的檔案和目錄。
- 使用適用於 Java 的檔案共用用戶端程式庫來使用 Azure 檔案儲存體:使用適用於 Java 的 Azure 儲存體檔案共用用戶端程式庫來處理檔案共用中的檔案和目錄。 此用戶端程式庫建置在 FileREST API 上。
- 使用 Azure 儲存體管理程式庫管理 Azure 檔案儲存體資源:使用 Azure 儲存體管理程式庫來管理儲存體帳戶中的檔案共用和其他資源。 管理程式庫是以 Azure 儲存體資源提供者 REST API 為基礎。
先決條件
- Azure 訂用帳戶 - 建立免費帳戶
- Azure 儲存體帳戶 - 建立儲存體帳戶
- Java 開發套件 (JDK) 8 版或更新版本
- 在此範例中,Apache Maven 用於專案管理
設定您的環境
備註
本文使用 Maven 建置工具來建置和執行範例程式碼。 其他建置工具,例如 Gradle,也可以與適用於 Java 的 Azure SDK 搭配使用。
使用 Maven 建立新的主控台應用程式,或開啟現有專案。 請依照下列步驟安裝套件並新增必要的 import 指令。
安裝套件
在文字編輯器中開啟 pom.xml 檔案。 透過 包含 BOM 檔案或 包含直接相依性來安裝套件。
包含 BOM 檔案
新增 azure-sdk-bom 以取得最新版本的程式庫相依性。 在下列程式碼片段中,將{bom_version_to_target}預留位置替換為版本號碼。 使用 azure-sdk-bom 可讓您不必指定每個個別相依性的版本。 若要深入瞭解 BOM,請參閱 Azure SDK BOM 自述文件。
<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>
將下列相依性元素新增至相依性群組。 需要 azure-identity 相依性才能對 Azure 服務進行無密碼連線。 請注意,資源管理程式構件不會包含在 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 java.io.*;
import java.nio.file.*;
使用 Java 檔案 I/O 程式庫處理 Azure 檔案儲存體
標準檔案 I/O 程式庫是存取和使用 Azure 檔案儲存體資源的最常見方式。 當您使用 SMB 或 NFS 掛接檔案共用時,作業系統會重新導向對本機檔案系統的 API 要求。 此方法可讓您使用標準檔案 I/O 程式庫 (例如 java.io 和 java.nio) 與共用中的檔案和目錄互動。
當您的應用程式需要時,請考慮使用 Java 檔案 I/O 程式庫:
- 應用程式相容性: 非常適合具有已使用 Java 檔案 I/O 程式庫的現有程式碼的企業營運應用程式。 您不需要重寫程式代碼,應用程式即可使用 Azure 檔案共用。
- 易於使用:Java 檔案 I/O 函式庫為開發人員所熟知且易於使用。 Azure 檔案服務的重要價值主張是,它會透過 SMB 和 NFS 公開原生文件系統 API。
在本節中,您將瞭解如何使用 Java 檔案 I/O 程式庫來使用 Azure 檔案儲存體資源。
如需詳細資訊和範例,請參閱下列資源:
掛接檔案共用
若要使用 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 檔案服務。 它可讓您呼叫 HTTPS 端點,以在檔案共享、目錄和檔案上執行作業。 FileREST API 是針對可能無法透過原生通訊協定使用的高延展性和進階功能所設計。 Azure SDK 提供用戶端程式庫,例如以 FileREST API 為基礎的 Java 檔案共用用戶端程式庫。
如果您的應用程式需要,請考慮使用 FileREST API 和檔案共用用戶端程式庫:
- 進階功能: 存取無法透過原生通訊協定使用的各項操作與功能。
- 自定義雲端整合: 建置與 Azure 檔案服務直接互動的自定義增值服務,例如備份、防病毒軟體或數據管理。
- 效能優化: 使用資料平面操作,在大規模情境中受益於效能優勢。
FileREST API 會將 Azure 檔案服務模型為資源階層,並建議用於在 目錄 或 檔案 層級執行的作業。 您應該偏好 儲存體資源提供者 REST API ,以進行在 檔案服務 或 檔案共用 層級執行的作業。
在本節中,您將瞭解如何使用 Java 的檔案共用用戶端程式庫來使用 Azure 檔案儲存體資源。
如需詳細資訊和範例,請參閱下列資源:
授權存取並建立用戶端
若要將應用程式連線到 Azure 檔案儲存體,請建立 ShareClient 物件。 此物件是您使用 Azure 檔案儲存體資源的起點。 下列程式碼範例示範如何使用不同的授權機制來建立 ShareClient 物件。
若要使用 Microsoft Entra ID 進行授權,您必須使用安全性主體。 您需要的安全性主體類型取決於應用程式的執行位置。 若要深入瞭解驗證案例,請參閱 使用 Java 和 Azure 身分識別進行 Azure 驗證。
若要使用本文中的程式碼範例,請將 Azure RBAC 內建角色 Storage File Data Privileged Contributor 指派至安全性主體。 此角色會針對所有已設定的儲存體帳戶,提供共用中所有資料的完整讀取、寫入、修改 ACL 和刪除存取權,而不論所設定的檔案/目錄層級 NTFS 權限為何。 如需詳細資訊,請參閱使用 Microsoft Entra ID 搭配 Azure 檔案儲存體 OAuth over REST 存取 Azure 檔案共用。
使用 DefaultAzureCredential 授權存取
授權存取並聯接至 Azure 檔案儲存體的簡單且安全的方法是藉由建立 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 身分識別用戶端程式庫中的其他類別來取得 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());
範例:使用檔案共用用戶端程式庫租用檔案
租用會在 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());
}
}
}
備註
OAuth 權杖,例如使用 DefaultAzureCredential 時取得的權杖,不能在檔案共用層級執行資料平面操作。 若要使用共用快照,必須使用帳戶金鑰授權用戶端物件。 在此程式碼範例中建立的 ShareClient 物件會使用連接字串,其中包含帳戶金鑰。
儲存帳戶金鑰或連接字串會帶來安全性風險。 當 Microsoft Entra 驗證無法使用時,您應該僅在此情況下使用這些功能。 若要深入瞭解如何在 Azure 金鑰保存庫中安全地儲存帳戶金鑰,請參閱 關於 Azure 金鑰保存庫受控儲存體帳戶金鑰。
使用 Azure 儲存體管理程式庫管理 Azure 檔案儲存體資源
Azure 儲存體管理程式庫是以 Azure 儲存體資源提供者 REST API 為基礎所建置。 Azure 儲存體資源提供者是以 Azure Resource Manager 為基礎的服務,並支援宣告式 (範本) 和命令式 (直接 API 呼叫) 方法。 Azure 記憶體資源提供者 REST API 會以程式設計方式存取 Azure 記憶體資源,包括檔案共用。 Azure SDK 提供以 Azure 記憶體資源提供者 REST API 為基礎的管理連結庫。
建議將管理程式庫用於在 檔案服務 或 檔案共用 層級執行的作業。 在本節中,您將瞭解如何使用 Azure 儲存體管理程式庫來管理 Azure 檔案儲存體資源。
Azure 儲存體管理程式庫是以 Azure 儲存體資源提供者 REST API 為基礎所建置。 Azure 儲存體資源提供者是以 Azure Resource Manager 為基礎的服務,並支援宣告式 (範本) 和命令式 (直接 API 呼叫) 方法。 Azure 記憶體資源提供者 REST API 會以程式設計方式存取 Azure 記憶體資源,包括檔案共用。 Azure SDK 提供以 Azure 記憶體資源提供者 REST API 為基礎的管理連結庫。
建議將管理程式庫用於在 檔案服務 或 檔案共用 層級執行的作業。 在本節中,您將瞭解如何使用 Azure 儲存體管理程式庫來管理 Azure 檔案儲存體資源。
範例:使用 Azure 儲存體管理程式庫建立檔案共用
下列程式碼範例示範如何建立最上層 AzureResourceManager 物件、向訂用帳戶註冊儲存體資源提供者,以及使用 Azure 儲存體管理程式庫建立檔案共用:
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 儲存體管理程式庫列出檔案共用和快照集
下列程式碼範例示範如何列出儲存體帳戶中的檔案共用和快照集:
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 檔案儲存體進行開發的詳細資訊,請參閱下列資源: