다음을 통해 공유


Azure Files 개발에 Java 사용

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(표준) 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 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를 기반으로 빌드되는 파일 공유 클라이언트 라이브러리(com.azure.storage.file.share)를 제공하여 친숙한 Java 프로그래밍 언어 패러다임을 통해 FileREST API 작업과 상호 작용할 수 있도록 합니다. 고객을 위해 부가 가치 클라우드 서비스 및 앱을 빌드하고 있으며 표준 파일 I/O 라이브러리를 통해 사용할 수 없는 고급 기능을 사용하려고 합니다.
스토리지 리소스 공급자 REST API ARM(Azure Resource Manager)을 사용하여 스토리지 계정 및 파일 공유를 관리합니다. 다양한 리소스 관리 작업을 위해 REST API 엔드포인트를 호출합니다. 앱 또는 서비스는 스토리지 계정 또는 파일 공유 만들기, 삭제 또는 업데이트와 같은 리소스 관리 작업을 수행해야 합니다.

이러한 접근 방식에 대한 일반적인 내용은 Azure Files를 사용한 애플리케이션 개발 개요를 참조하세요.

이 문서에서는 다음 방법을 사용하여 Azure Files 리소스를 사용하는 방법에 중점을 둡니다.

필수 조건

환경 설정

비고

이 문서에서는 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 서비스에 대한 암호 없는 연결에는 azure-identity 종속성이 필요합니다. 리소스 관리자 아티팩트가 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 명령문을 포함하세요

그런 다음, 코드 파일을 열고 필요한 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 Files를 작업하기

표준 파일 I/O 라이브러리는 Azure Files 리소스에 액세스하고 작업하는 가장 일반적인 방법입니다. SMB 또는 NFS를 사용하여 파일 공유를 탑재하면 운영 체제에서 로컬 파일 시스템에 대한 API 요청을 리디렉션합니다. 이 방법을 사용하면 표준 파일 I/O 라이브러리(예: java.iojava.nio)를 사용하여 공유의 파일 및 디렉터리와 상호 작용할 수 있습니다.

앱에 다음이 필요한 경우 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 기본 제공 역할 스토리지 파일 데이터 권한 있는 기여자를 보안 주체에 할당합니다. 이 역할은 설정된 파일/디렉터리 수준 NTFS 권한에 관계없이 구성된 모든 스토리지 계정에 대한 공유의 모든 데이터에 대한 전체 읽기, 쓰기, 수정 및 삭제 액세스를 제공합니다. 자세한 내용은 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 ID 클라이언트 라이브러리의 다른 클래스를 사용하여 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());
        }
    }
}

비고

OAuth 토큰(예: 사용 DefaultAzureCredential시 가져온 토큰)은 파일 공유 수준에서 데이터 평면 작업에 허용되지 않습니다. 공유 스냅샷을 사용하려면 계정 키를 사용하여 클라이언트 개체에 권한을 부여해야 합니다. 이 코드 예제에서 만든 개체는 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 개체를 만들고, Storage 리소스 공급자를 구독에 등록하고, 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 클래스를 사용하여 파일 공유 속성을 구성할 수 있습니다. 이전 예제에서는 파일 공유를 만들 때 공유 할당량을 설정하는 방법을 보여줍니다. 기존 파일 공유를 업데이트하려면 업데이트하려는 속성을 가진 FileShareInner 객체를 준비하고 fileShare.update()을 호출하여 전달하십시오.

비고

등록 작업을 수행하려면 다음 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를 사용하여 개발하는 방법에 대한 자세한 내용은 다음 리소스를 참조하세요.