使用 TypeScript 设置或更改块 blob 的访问层

本文介绍了如何通过适用于 JavaScript 的 Azure 存储客户端库设置或更改 blob 的访问层

先决条件

  • 本文中的示例假设你已经设置了一个项目来使用适用于 JavaScript 的 Azure Blob 存储客户端库。 要了解如何设置项目(包括包安装、导入模块,以及创建授权客户端对象来使用数据资源),请参阅开始使用 Azure Blob 存储和 TypeScript
  • 授权机制必须具有设置 blob 的访问层的权限。 若要了解详细信息,请参阅以下 REST API 操作的授权指南:

关于块 blob 访问层

要管理存储需求产生的成本,根据数据的访问频率和所需的保留期来整理数据会很有帮助。 Azure 存储提供不同的访问层,以便你可以基于使用方式,以最具成本效益的方式存储 Blob 数据。

Blob 数据的访问层

Azure 存储访问层包括:

  • 热层 - 适用于存储经常访问或修改的数据的联机层。 热层的存储成本最高,但访问成本最低。
  • 冷层 - 适用于存储不经常访问或修改的数据的联机层。 冷层中的数据应至少存储 30 天。 与热层相比,冷层的存储成本较低,访问成本较高。
  • 寒层 - 适用于存储不经常访问或修改的数据的联机层。 寒层中的数据应至少存储 90 天。 与冷层相比,寒层的存储成本较低,访问成本较高。
  • 存档层 - 适用于存储极少访问且延迟要求(以小时计)不严格的数据的脱机层。 存档层中的数据应至少存储 180 天。

若要详细了解访问层,请参阅 Blob 数据的访问层

当 Blob 位于存档访问层时,则会将其视为处于脱机状态,无法读取或修改。 若要读取或修改存档 Blob 中的数据,必须先将 Blob 解除冻结到联机层。 若要详细了解如何将 Blob 从存档层解除冻结到联机层,请参阅从存档层解除冻结 Blob

限制

仅允许在块 Blob 上设置访问层。 若要了解有关设置块 Blob 访问层的限制的详细信息,请参阅设置 Blob 层 (REST API)

注意

若要使用 TypeScript 将访问层设置为 Cold,必须至少使用客户端库版本 12.13.0。

在上传期间设置 Blob 的访问层

若要将 Blob 上传到特定访问层,请使用 BlockBlobUploadOptionstier 属性选项包括:HotCoolArchive

async function uploadWithAccessTier(
  containerClient: ContainerClient
): Promise<BlockBlobClient> {
  // Create blob
  const timestamp = Date.now();
  const blobName = `myblob-${timestamp}`;
  console.log(`creating blob ${blobName}`);

  const fileContentsAsString = `Hello from a string`;

  const tags: Tags = {};

  // upload blob to `hot` access tier
  const uploadOptions: BlockBlobUploadOptions = {
    // access tier setting
    // 'Hot', 'Cool', or 'Archive'
    tier: 'Cool',

    // other properties
    metadata: undefined,
    tags
  };

  // Create blob client from container client
  const blockBlobClient: BlockBlobClient =
    await containerClient.getBlockBlobClient(blobName);

  // Upload string
  const uploadResult = await blockBlobClient.upload(
    fileContentsAsString,
    fileContentsAsString.length,
    uploadOptions
  );

  if (uploadResult.errorCode) throw Error(uploadResult.errorCode);

  // Return client to continue with other operations
  return blockBlobClient;
}

上传后更改 Blob 的访问层

若要在 Blob 上传到存储后更改其访问层,请使用 setAccessTier。 除了该层外,还可以设置 BlobSetTierOptions 属性解除冻结优先级,使块 Blob 脱离存档状态。 可能的值为 HighStandard

async function main(blockBlobClient: BlockBlobClient): Promise<void> {
  const options: BlobGetPropertiesOptions = {};

  // Get current access tier
  const { errorCode, accessTier } = await blockBlobClient.getProperties(
    options
  );
  if (!errorCode) {
    console.log(`Current access tier: ${accessTier}`);
  }

  // 'Hot', 'Cool', or 'Archive'
  const newAccessTier = 'Cool';

  // Rehydrate priority: 'High' or 'Standard'
  const tierOptions: BlobSetTierOptions = {
    rehydratePriority: 'High'
  };

  const result: BlobSetTierResponse = await blockBlobClient.setAccessTier(
    newAccessTier,
    tierOptions
  );

  if (!result?.errorCode) {
    console.log(`Change to access was successful`);
  } else {
    console.log(result);
  }
}

将 Blob 复制到不同的访问层

使用 BlobClient.beginCopyFromURL 方法复制 Blob。 若要在复制操作期间更改访问层,请使用 BlobBeginCopyFromURLOptionstier 属性并指定与源 Blob 不同的访问

async function copyBlobWithDifferentAccessTier(
  containerClient: ContainerClient
): Promise<void> {
  // create blob clients
  const sourceBlobClient: BlobClient = await containerClient.getBlobClient(
    originalBlob
  );
  const destinationBlobClient: BlobClient = await containerClient.getBlobClient(
    copyBlob
  );

  const copyOptions: BlobBeginCopyFromURLOptions = { tier: 'Hot' };

  // start copy, access tiers include `Hot`, `Cool`, `Archive`
  const copyPoller = await destinationBlobClient.beginCopyFromURL(
    sourceBlobClient.url,
    copyOptions
  );
  console.log('start copy from original to copy');

  // wait until done
  await copyPoller.pollUntilDone();
  console.log('copy finished');
}

使用批处理更改多个 Blob 的访问层

批处理表示对 Blob 执行的聚合操作集,例如删除设置访问层。 需要传入正确的凭据才能成功执行每项操作。 在本例中,同一个容器中的一组 Blob 使用相同的凭据。

创建 BlobBatchClient。 使用客户端通过 createBatch() 方法创建批处理。 当批准备就绪后,提交批进行处理。 使用返回的结构验证每个 Blob 的操作是否成功。

async function batchChangeAccessTier(
  containerClient: ContainerClient
): Promise<void> {
  // Prep array
  const blockBlobCount = 3;
  const blockBlobClients: BlockBlobClient[] = new Array(blockBlobCount);

  // Create container and blobs in `Hot` tier
  await prepContainer(containerClient, blockBlobCount, blockBlobClients);

  // Blob batch client and batch
  const containerScopedBatchClient: BlobBatchClient =
    containerClient.getBlobBatchClient();
  const blobBatch: BlobBatch = containerScopedBatchClient.createBatch();

  // Assemble batch to set tier to `Cool` tier
  for (let i = 0; i < blockBlobCount; i++) {
    await blobBatch.setBlobAccessTier(
      blockBlobClients[i].url,
      sharedKeyCredential,
      'Cool',
      {}
    );
  }

  // Submit batch request and verify response
  const resp = await containerScopedBatchClient.submitBatch(blobBatch, {});

  if (resp.errorCode) throw Error(resp.errorCode);

  console.log(
    `Requested ${blockBlobCount}, batched ${resp.subResponses.length}, success ${resp.subResponsesSucceededCount}, failure ${resp.subResponsesFailedCount}`
  );

  // Examine each batch item
  for (let i = 0; i < blockBlobCount; i++) {
    // Check blob tier set properly
    const resp2 = await blockBlobClients[i].getProperties();

    if (resp2.errorCode) throw Error(resp2.errorCode);

    console.log(
      `[${i}] access tier ${resp2.accessTier}, status ${resp.subResponses[i].status}, message ${resp.subResponses[i].statusMessage}`
    );
  }
}

代码示例

后续步骤