다음을 통해 공유


데이터 이동 라이브러리를 사용하여 데이터 전송

Azure Storage 데이터 이동 라이브러리는 Blob 및 파일의 고성능 업로드, 다운로드 및 복사 작업을 위해 설계된 플랫폼 간 오픈 소스 라이브러리입니다. 데이터 이동 라이브러리는 .NET용 Azure Storage 클라이언트 라이브러리에서 사용할 수 없는 편리한 방법을 제공합니다. 이러한 메서드를 사용하면 병렬 작업 수를 설정하고, 전송 진행률을 추적하고, 취소된 전송을 다시 시작하는 등의 작업을 수행할 수 있습니다.

데이터 이동 라이브러리는 .NET에만 사용할 수 있으며 Azure Blob Storage 및 Azure Files만 지원합니다. You should consider these limitations and other known issues when deciding whether to use the Data Movement library.

If you're migrating code from the older Microsoft.Azure.Storage.DataMovement library (version 2.X.X) to the current Azure.Storage.DataMovement library (version 12.X.X), see the Migration guide.

API 참조 문서 | 소스 코드 | 패키지(NuGet) | 샘플: Blobs / Files.Shares

Prerequisites

환경 설정

기존 프로젝트가 없는 경우, 이 섹션에서는 .NET용 Azure Blob Storage 클라이언트 라이브러리를 사용해서 작동하도록 프로젝트를 설정하는 방법을 보여 줍니다. 이 단계에는 패키지 설치, using 지시문 추가 및 권한이 있는 클라이언트 개체 만들기가 포함됩니다.

Install packages

프로젝트 디렉터리에서 명령을 사용하여 dotnet add package Azure Storage Data Movement 클라이언트 라이브러리 및 Azure Identity 클라이언트 라이브러리에 대한 패키지를 설치합니다. The Azure.Identity package is needed for passwordless connections to Azure services.

dotnet add package Azure.Storage.DataMovement
dotnet add package Azure.Storage.DataMovement.Blobs
dotnet add package Azure.Identity

To work with extension library for Azure Files, install the Azure.Storage.DataMovement.Files.Shares package:

dotnet add package Azure.Storage.DataMovement.Files.Shares

using 지시문 추가

이 문서의 코드 예제를 실행하려면 다음 using 지시문을 추가합니다.

using Azure;
using Azure.Core;
using Azure.Identity;
using Azure.Storage.DataMovement;
using Azure.Storage.DataMovement.Blobs;

Azure Files용 확장 라이브러리를 사용하는 경우 다음 using 지시문을 추가합니다.

using Azure.Storage.DataMovement.Files.Shares;

Authorization

권한 부여 메커니즘에는 업로드, 다운로드 또는 복사 작업을 수행하는 데 필요한 권한이 있어야 합니다. Microsoft Entra ID로 권한을 부여하려면(권장) Azure RBAC 기본 제공 역할 Storage Blob 데이터 기여자 이상이 필요합니다.

데이터 이동 라이브러리 정보

Azure Storage 데이터 이동 라이브러리는 일반적인 클라이언트 라이브러리와 Azure Blob Storage 및 Azure Files용 확장 라이브러리로 구성됩니다. 공통 라이브러리는 데이터를 전송하기 위한 핵심 기능을 제공하는 반면 확장 라이브러리는 Blob Storage 및 Azure Files와 관련된 기능을 제공합니다. 자세한 내용은 다음 리소스를 참조하세요.

TransferManager 개체 만들기

TransferManager is the main class for starting and controlling all types of transfers, including upload, download, and copy. 이 섹션에서는 로컬 파일 시스템, Blob Storage 또는 Azure Files로 작업할 개체를 만드는 TransferManager 방법을 알아봅니다.

Note

Azure SDK 클라이언트 관리를 위한 모범 사례는 클라이언트를 싱글톤으로 처리하는 것입니다. 즉, 클래스에는 한 번에 하나의 개체만 있습니다. 지정된 생성자 매개 변수 또는 클라이언트 옵션 집합에 대해 둘 이상의 클라이언트 인스턴스를 유지할 필요가 없습니다.

다음 코드는 개체를 만드는 방법을 보여줍니다.TransferManager

TransferManager transferManager = new(new TransferManagerOptions());

You can optionally provide an instance of TransferManagerOptions to the constructor, which applies certain configuration options to all transfers started by the TransferManager object. 사용할 수 있는 구성 옵션은 다음과 같습니다.

  • CheckpointStoreOptions: Optional. 전송을 다시 시작하려면 전송 상태를 저장하는 데 사용되는 검사점을 만드는 옵션을 정의합니다.
  • Diagnostics: Gets the transfer manager diagnostic options.
  • 전송 중에 오류가 처리되는 방법을 정의합니다. 기본값은 StopOnAnyFailure입니다. Default is StopOnAnyFailure.
  • MaximumConcurrency: The maximum number of workers that can be used in a parallel transfer.
  • ProvidersForResuming: Resource providers for the transfer manager to use in resuming a transfer. 사용 중인 각 스토리지 공급자에 대해 하나의 공급자가 필요합니다. 자세한 내용은 기존 전송 다시 시작을 참조하세요.

StorageResource 개체 만들기

StorageResource is the base class for all storage resources, including blobs and files. 개체를 StorageResource 만들려면 다음 공급자 클래스 중 하나를 사용합니다.

StorageResource Blob Storage에 대한 개체 만들기

다음 코드에서는 다음을 StorageResource 사용하여 UriBlob 컨테이너 및 Blob에 대한 개체를 만드는 방법을 보여 줍니다.

// Create a token credential
TokenCredential tokenCredential = new DefaultAzureCredential();

BlobsStorageResourceProvider blobsProvider = new(tokenCredential);

// Get a container resource
StorageResource container = await blobsProvider.FromContainerAsync(
    new Uri("http://<storage-account-name>.blob.core.windows.net/sample-container"));

// Get a block blob resource - default is block blob
StorageResource blockBlob = await blobsProvider.FromBlobAsync(
    new Uri("http://<storage-account-name>.blob.core.windows.net/sample-container/sample-block-blob"),
    new BlockBlobStorageResourceOptions());

// Use a similar approach to get a page blob or append blob resource

You can also create a StorageResource object using a client object from Azure.Storage.Blobs.

// Create a token credential
TokenCredential tokenCredential = new DefaultAzureCredential();

BlobContainerClient blobContainerClient = new(
    new Uri("https://<storage-account-name>.blob.core.windows.net/sample-container"),
    tokenCredential);
StorageResource containerResource = BlobsStorageResourceProvider.FromClient(blobContainerClient);

BlockBlobClient blockBlobClient = blobContainerClient.GetBlockBlobClient("sample-block-blob");
StorageResource blockBlobResource = BlobsStorageResourceProvider.FromClient(blockBlobClient);

// Use a similar approach to get a page blob or append blob resource

새 전송 시작

모든 전송은 원본과 대상을 지정해야 합니다. 원본과 대상은 모두 형식 StorageResource이며, 형식 중 하나 StorageResourceContainer 또는 StorageResourceItem.일 수 있습니다. 지정된 전송의 경우 원본과 대상은 동일한 종류여야 합니다. 예를 들어 원본이 Blob 컨테이너인 경우 대상은 Blob 컨테이너여야 합니다.

다음 메서드를 호출하여 새 전송을 시작할 수 있습니다.

This method returns a TransferOperation object that represents the transfer. 개체를 TransferOperation 사용하여 전송 진행률을 모니터링하거나 전송 ID를 가져올 수 있습니다. 전송 ID는 전송을 다시 시작하거나 전송을 일시 중지하는 데 필요한 전송 에 대한 고유 식별자입니다.

You can optionally provide an instance of TransferOptions to StartTransferAsync or ResumeTransferAsync, which applies certain configuration options to a specific transfer. 사용할 수 있는 구성 옵션은 다음과 같습니다.

  • CreationMode: Configures the behavior when a transfer encounters a resource that already exists. 새 전송을 FailIfExists 시작할 때 기본값으로 설정됩니다. 전송을 다시 시작하면 기본값이 달라질 수 있습니다. 전송이 시작될 때 성공적으로 열거된 CreationMode 모든 리소스의 경우 기본값은 사용된 초기 값으로 설정됩니다. 나머지 리소스의 경우 일반 기본값이 적용됩니다.
  • InitialTransferSize: The size of the first range request in bytes. 이 제한보다 작은 단일 전송 크기는 단일 요청으로 업로드되거나 다운로드됩니다. Transfers larger than this limit continue being downloaded or uploaded in chunks of size MaximumTransferChunkSize. 기본값은 32MiB입니다. 전송을 다시 시작할 때 기본값은 전송이 처음 시작될 때 지정된 값입니다.
  • MaximumTransferChunkSize: The maximum size to use for each chunk when transferring data in chunks. 기본값은 4MiB입니다. 전송을 다시 시작할 때 기본값은 전송이 처음 시작될 때 지정된 값입니다.
  • ProgressHandlerOptions: Optional. ProgressHandler의 동작을 변경하는 옵션입니다.

예: Blob 컨테이너에 로컬 디렉터리 업로드

다음 코드 예제에서는 Blob 컨테이너에 로컬 디렉터리를 업로드하기 위해 새 전송을 시작하는 방법을 보여줍니다.

// Create a token credential
TokenCredential tokenCredential = new DefaultAzureCredential();

TransferManager transferManager = new(new TransferManagerOptions());

BlobsStorageResourceProvider blobsProvider = new(tokenCredential);

string localDirectoryPath = "C:/path/to/directory";
Uri blobContainerUri = new Uri("https://<storage-account-name>.blob.core.windows.net/sample-container");

TransferOperation transferOperation = await transferManager.StartTransferAsync(
    sourceResource: LocalFilesStorageResourceProvider.FromDirectory(localDirectoryPath),
    destinationResource: await blobsProvider.FromContainerAsync(blobContainerUri));
await transferOperation.WaitForCompletionAsync();

예: 컨테이너 또는 Blob 복사

데이터 이동 라이브러리를 사용하여 두 StorageResource 인스턴스 간에 복사할 수 있습니다. Blob 리소스의 경우 전송은 서버-서버 복사를 수행하는 URL에서 Blob 배치 작업을 사용합니다.

다음 코드 예제에서는 새 전송을 시작하여 원본 Blob 컨테이너의 모든 Blob을 대상 Blob 컨테이너에 복사하는 방법을 보여 줍니다. 대상 컨테이너는 이미 있어야 합니다. In this example, we set CreationMode to OverwriteIfExists to overwrite any destination blobs that already exist. 앱의 CreationMode 요구 사항에 따라 속성을 조정할 수 있습니다.

Uri sourceContainerUri = new Uri("https://<storage-account-name>.blob.core.windows.net/source-container");
Uri destinationContainerUri = new Uri("https://<storage-account-name>.blob.core.windows.net/dest-container");

TransferOperation transferOperation = await transferManager.StartTransferAsync(
    sourceResource: await blobsProvider.FromContainerAsync(
        sourceContainerUri,
        new BlobStorageResourceContainerOptions()
        {
            BlobPrefix = "source/directory/prefix"
        }),
    destinationResource: await blobsProvider.FromContainerAsync(
        destinationContainerUri,
        new BlobStorageResourceContainerOptions()
        {
            // All source blobs are copied as a single type of destination blob
            // Defaults to block blob, if not specified
            BlobType = BlobType.Block,
            BlobPrefix = "destination/directory/prefix"
        }),
    transferOptions: new TransferOptions()
    {
        CreationMode = StorageResourceCreationMode.OverwriteIfExists,
    }
);
await transferOperation.WaitForCompletionAsync();

다음 코드 예제에서는 원본 Blob을 대상 Blob에 복사하는 새 전송을 시작하는 방법을 보여 있습니다. In this example, we set CreationMode to OverwriteIfExists to overwrite the destination blob if it already exists. 앱의 CreationMode 요구 사항에 따라 속성을 조정할 수 있습니다.

Uri sourceBlobUri = new Uri(
    "https://<storage-account-name>.blob.core.windows.net/source-container/source-blob");
Uri destinationBlobUri = new Uri(
    "https://<storage-account-name>.blob.core.windows.net/dest-container/dest-blob");

TransferOperation transferOperation = await transferManager.StartTransferAsync(
    sourceResource: await blobsProvider.FromBlobAsync(sourceBlobUri),
    destinationResource: await blobsProvider.FromBlobAsync(destinationBlobUri, new BlockBlobStorageResourceOptions()),
    transferOptions: new TransferOptions()
    {
        CreationMode = StorageResourceCreationMode.OverwriteIfExists,
    }
);
await transferOperation.WaitForCompletionAsync();

기존 전송 다시 시작

디스크로 전송 진행률을 유지하면 데이터 이동 라이브러리를 사용하면 완료 전에 실패했거나 취소되거나 일시 중지된 전송을 다시 시작할 수 있습니다. 전송 TransferManager 을 다시 시작하려면 지속형 데이터에서 전송을 다시 조립할 수 있는 인스턴스로 개체를 구성 StorageResourceProvider 해야 합니다. You can use the ProvidersForResuming property of the TransferManagerOptions class to specify the providers.

다음 코드 예제에서는 로컬 파일 시스템과 Blob Storage 간에 전송을 다시 열 수 있는 개체를 초기화하는 TransferManager 방법을 보여 줍니다.

// Create a token credential
TokenCredential tokenCredential = new DefaultAzureCredential();

TransferManager transferManager = new(new TransferManagerOptions()
{
    ProvidersForResuming = new List<StorageResourceProvider>()
    {
        new BlobsStorageResourceProvider(tokenCredential)
    }
});

전송을 다시 시작하려면 다음 메서드를 호출합니다.

다시 시작하려는 전송의 전송 ID를 제공합니다. 전송 ID는 전송이 시작될 때 개체의 일부로 반환되는 전송에 TransferOperation 대한 고유 식별자입니다. If you don't know the transfer ID value, you can call TransferManager.GetTransfersAsync to find the transfer and its corresponding ID.

다음 코드 예제에서는 전송을 다시 시작하는 방법을 보여줍니다.

TransferOperation resumedTransfer = await transferManager.ResumeTransferAsync(transferId: ID);

Note

The ___location of the persisted transfer data is different than the default ___location if TransferCheckpointStoreOptions is set as part of TransferManagerOptions. 사용자 지정 검사점 저장소를 사용하여 기록된 전송을 다시 시작하려면 전송을 다시 시작하는 개체에 대해 TransferManager 동일한 검사점 저장소 옵션을 제공해야 합니다.

전송 진행률 모니터링

앱의 요구 사항에 따라 여러 메커니즘을 통해 전송을 모니터링하고 관찰할 수 있습니다. 이 섹션에서는 개체를 사용하여 TransferOperation 전송 진행률을 모니터링하는 방법과 이벤트를 사용하여 TransferOptions 전송을 모니터링하는 방법을 알아봅니다.

예: 개체를 TransferOperation 사용하여 전송 진행률 모니터링

메서드에서 반환된 개체를 TransferOperation 사용하여 전송 진행률을 모니터링할 StartTransferAsync 수 있습니다. You can also call TransferManager.GetTransfersAsync to enumerate all transfers for a TransferManager object.

다음 코드 예제에서는 모든 전송을 반복하고 각 전송의 상태를 로그 파일에 쓰는 방법을 보여 줍니다.

async Task CheckTransfersAsync(TransferManager transferManager)
{
    await foreach (TransferOperation transfer in transferManager.GetTransfersAsync())
    {
        using StreamWriter logStream = File.AppendText("path/to/log/file");
        logStream.WriteLine(Enum.GetName(typeof(TransferState), transfer.Status.State));
    }
}

TransferStatus defines the status of the transfer job. TransferStatus 에는 다음 속성이 포함됩니다.

Property Type Description
HasCompletedSuccessfully Boolean 오류 또는 건너뛴 항목 없이 전송이 성공적으로 완료되었는지 여부를 나타냅니다.
HasFailedItems Boolean 전송에 오류 항목이 있는지를 나타냅니다. 설정 true하면 전송에 하나 이상의 오류 항목이 있습니다. 설정 false하면 전송에 현재 오류가 없습니다.
HasSkippedItems Boolean 전송에 건너뛴 항목이 있는지를 나타냅니다. 이 항목으로 true설정하면 전송에 건너뛴 항목이 하나 이상 있습니다. 설정 false하면 전송에 현재 건너뛴 항목이 없습니다. It's possible to never have any items skipped if SkipIfExists isn't enabled in TransferOptions.CreationMode.
State TransferState 전송에 사용할 수 있는 상태의 형식을 정의합니다. See TransferState for details.

예: 이벤트를 사용하여 TransferOptions 전송 진행률 모니터링

You can monitor transfer progress by listening for events provided by the TransferOptions class. The TransferOptions instance is passed to the StartTransferAsync method and provides events that are triggered when a transfer completes, fails, is skipped, or changes status.

다음 코드 예제에서는 다음을 사용하여 TransferOptions전송 완료 이벤트를 수신 대기하는 방법을 보여줍니다.

async Task<TransferOperation> ListenToTransfersAsync(
    TransferManager transferManager,
    StorageResource source,
    StorageResource destination)
{
    TransferOptions transferOptions = new();
    transferOptions.ItemTransferCompleted += (TransferItemCompletedEventArgs args) =>
    {
        using (StreamWriter logStream = File.AppendText("path/to/log/file"))
        {
            logStream.WriteLine($"File Completed Transfer: {args.Source.Uri.AbsoluteUri}");
        }
        return Task.CompletedTask;
    };
    return await transferManager.StartTransferAsync(
        source,
        destination,
        transferOptions);
}

에 대한 확장 메서드 사용 BlobContainerClient

For applications with existing code that uses the BlobContainerClient class from Azure.Storage.Blobs, you can use extension methods to start transfers directly from a BlobContainerClient object. The extension methods are provided in the BlobContainerClientExtensions class (or ShareDirectoryClientExtensions for Azure Files), and provide some of the benefits of using TransferManager with minimal code changes. 이 섹션에서는 확장 메서드를 사용하여 개체에서 BlobContainerClient 전송을 수행하는 방법을 알아봅니다.

Install the Azure.Storage.Blobs package if you don't have it already:

dotnet add package Azure.Storage.Blobs

코드 파일의 맨 위에 다음 using 지시문을 추가합니다.

using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;

다음 코드 예제에서는 명명BlobContainerClientsample-container Blob 컨테이너에 대해 인스턴스화하는 방법을 보여줍니다.

// Create a token credential
TokenCredential tokenCredential = new DefaultAzureCredential();

BlobServiceClient client = new BlobServiceClient(
    new Uri("https://<storage-account-name>.blob.core.windows.net"),
    tokenCredential);

BlobContainerClient containerClient = client.GetBlobContainerClient("sample-container");

다음 코드 예제에서는 로컬 디렉터리 콘텐츠를 업로드하여 다음을 sample-container 사용하는 UploadDirectoryAsync방법을 보여 줍니다.

TransferOperation transfer = await containerClient
    .UploadDirectoryAsync(WaitUntil.Started, "local/directory/path");

await transfer.WaitForCompletionAsync();

다음 코드 예제에서는 다음을 사용하여 sample-container로컬 디렉터리에 콘텐츠를 DownloadToDirectoryAsync 다운로드하는 방법을 보여 줍니다.

TransferOperation transfer = await containerClient
    .DownloadToDirectoryAsync(WaitUntil.Started, "local/directory/path");

await transfer.WaitForCompletionAsync();

확장 메서드에 대한 BlobContainerClient자세한 내용은 BlobContainerClient의 확장을 참조 하세요.

Next step