我正在使用 Azure 存储来提供静态文件 blob,但我想在提供时向文件/blob 添加一个 Cache-Control 和 Expires 标头,以降低带宽成本。
CloudXplorer和 Cerebrata 的Cloud Storage Studio等应用程序提供了在容器和 blob 上设置元数据属性的选项,但在尝试添加 Cache-Control 时会感到不安。
任何人都知道是否可以为文件设置这些标题?
我正在使用 Azure 存储来提供静态文件 blob,但我想在提供时向文件/blob 添加一个 Cache-Control 和 Expires 标头,以降低带宽成本。
CloudXplorer和 Cerebrata 的Cloud Storage Studio等应用程序提供了在容器和 blob 上设置元数据属性的选项,但在尝试添加 Cache-Control 时会感到不安。
任何人都知道是否可以为文件设置这些标题?
我不得不对大约 600k blob 运行批处理作业,并发现了 2 件真正有帮助的事情:
并行运行操作。.net v4 中的任务并行库 (TPL) 使这变得非常容易。下面是为容器中的每个 blob 并行设置缓存控制标头的代码:
// get the info for every blob in the container
var blobInfos = cloudBlobContainer.ListBlobs(
new BlobRequestOptions() { UseFlatBlobListing = true });
Parallel.ForEach(blobInfos, (blobInfo) =>
{
// get the blob properties
CloudBlob blob = container.GetBlobReference(blobInfo.Uri.ToString());
blob.FetchAttributes();
// set cache-control header if necessary
if (blob.Properties.CacheControl != YOUR_CACHE_CONTROL_HEADER)
{
blob.Properties.CacheControl = YOUR_CACHE_CONTROL_HEADER;
blob.SetProperties();
}
});
这是使用 Net 5 和 V12 of Azure.Storage.Blobs 的 Joel Fillmore 答案的更新版本。(顺便说一句:如果可以在父容器上设置默认标题属性,那不是很好吗?)
Azure 可以运行“WebJobs”,而不是创建网站并使用 WorkerRole。您可以在存储帐户所在的同一数据中心的网站上按需运行任何可执行文件,以设置缓存标头或任何其他标头字段。
下面的代码为每个容器运行一个单独的任务,我每分钟最多更新 100K 标头(取决于一天中的时间?)。没有出口费用。
using Azure;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace AzureHeaders
{
class Program
{
private static string connectionString = "DefaultEndpointsProtocol=https;AccountName=REPLACE_WITH_YOUR_CONNECTION_STRING";
private static string newCacheControl = "public, max-age=7776001"; // 3 months
private static string[] containersToProcess = { "container1", "container2" };
static async Task Main(string[] args)
{
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
var tasks = new List<Task>();
foreach (var container in containersToProcess)
{
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(container);
tasks.Add(Task.Run(() => UpdateHeaders(containerClient, 1000))); // I have no idea what segmentSize should be!
}
Task.WaitAll(tasks.ToArray());
}
private static async Task UpdateHeaders(BlobContainerClient blobContainerClient, int? segmentSize)
{
int processed = 0;
int failed = 0;
try
{
// Call the listing operation and return pages of the specified size.
var resultSegment = blobContainerClient.GetBlobsAsync()
.AsPages(default, segmentSize);
// Enumerate the blobs returned for each page.
await foreach (Azure.Page<BlobItem> blobPage in resultSegment)
{
var tasks = new List<Task>();
foreach (BlobItem blobItem in blobPage.Values)
{
BlobClient blobClient = blobContainerClient.GetBlobClient(blobItem.Name);
tasks.Add(UpdateOneBlob(blobClient));
processed++;
}
Task.WaitAll(tasks.ToArray());
Console.WriteLine($"Container {blobContainerClient.Name} processed: {processed}");
}
}
catch (RequestFailedException e)
{
Console.WriteLine(e.Message);
failed++;
}
Console.WriteLine($"Container {blobContainerClient.Name} processed: {processed}, failed: {failed}");
}
private static async Task UpdateOneBlob(BlobClient blobClient) {
Response<BlobProperties> propertiesResponse = await blobClient.GetPropertiesAsync();
BlobHttpHeaders httpHeaders = new BlobHttpHeaders
{
// copy any existing headers you wish to preserve
ContentType = propertiesResponse.Value.ContentType,
ContentHash = propertiesResponse.Value.ContentHash,
ContentEncoding = propertiesResponse.Value.ContentEncoding,
ContentDisposition = propertiesResponse.Value.ContentDisposition,
// update CacheControl
CacheControl = newCacheControl
};
await blobClient.SetHttpHeadersAsync(httpHeaders);
}
}
}
最新版本的Cerebrata Cloud Storage Studio v2011.04.23.00 支持在单个 blob 对象上设置缓存控制。右键单击 blob 对象,选择“查看/编辑 Blob 属性”,然后设置Cache-Control
属性值。(例如public, max-age=2592000
)。
如果您使用 curl 检查 blob 对象的 HTTP 标头,您将看到缓存控制标头返回您设置的值。
有时,最简单的答案就是最好的答案。如果只想管理少量 blob,可以使用Azure 管理更改 blob 的标头/元数据。
在该编辑窗口中,您可以自定义Cache Control、Content Encoding、Content Language等。
注意:您目前无法从Azure 门户编辑此数据
最新的CloudBerry Explorer现在支持 Cache-Control: http ://www.cloudberrylab.com/forum/default.aspx?g=posts&t=3047
这是使用 WindowsAzure.Storage v9.3.3 的 Joel Fillmore 答案的更新版本。请注意,ListBlobsSegmentedAsync 返回的页面大小为 5,000,这就是使用 BlobContinuationToken 的原因。
public async Task BackfillCacheControlAsync()
{
var container = await GetCloudBlobContainerAsync();
BlobContinuationToken continuationToken = null;
do
{
var blobInfos = await container.ListBlobsSegmentedAsync(string.Empty, true, BlobListingDetails.None, null, continuationToken, null, null);
continuationToken = blobInfos.ContinuationToken;
foreach (var blobInfo in blobInfos.Results)
{
var blockBlob = (CloudBlockBlob)blobInfo;
var blob = await container.GetBlobReferenceFromServerAsync(blockBlob.Name);
if (blob.Properties.CacheControl != "public, max-age=31536000")
{
blob.Properties.CacheControl = "public, max-age=31536000";
await blob.SetPropertiesAsync();
}
}
}
while (continuationToken != null);
}
private async Task<CloudBlobContainer> GetCloudBlobContainerAsync()
{
var storageAccount = CloudStorageAccount.Parse(_appSettings.AzureStorageConnectionString);
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("uploads");
return container;
}
这是一个批处理/unix 脚本,适用于不使用 PowerShell 的 Windows 机器上的每个人。以下脚本循环遍历所有 blob,并分别在 blob 上设置 Content-Cache 属性(Cache-Control http 标头)。
不幸的是,没有办法同时在多个 blob 上设置属性,因此这是一项耗时的任务。每个 blob 通常需要大约 1-2 秒。但是,正如 Jay Borseth 指出的那样,如果从与您的存储帐户位于同一数据中心的服务器上运行该过程,则会显着加快该过程。
# Update Azure Blob Storage blob's cache-control headers
# /content-cache properties
#
# Quite slow, since there is no `az storage blob update-batch`
#
# Created by Jon Tingvold, March 2021
#
#
# If you want progress, you need to install pv:
# >>> brew install pv # Mac
# >>> sudo apt install pv # Ubuntu
#
set -e # exit when any command fails
AZURE_BLOB_CONNECTION_STRING='DefaultEndpointsProtocol=https;EndpointSuffix=core.windows.net;AccountName=XXXXXXXXXXXX;AccountKey=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX=='
CONTAINER_NAME=main
BLOB_PREFIX='admin/'
CONTENT_CACHE='max-age=3600'
NUM_RESULTS=10000000 # Defaults to 5000
BLOB_NAMES=$(az storage blob list --connection-string $AZURE_BLOB_CONNECTION_STRING --container-name $CONTAINER_NAME --query '[].name' --output tsv --num-results $NUM_RESULTS --prefix $BLOB_PREFIX)
NUMBER_OF_BLOBS=$(echo $BLOB_NAMES | wc -w)
echo "Ask Azure for files in Blob Storage ..."
echo "Set content-cache on $NUMBER_OF_BLOBS blobs ..."
for BLOB_NAME in $BLOB_NAMES
do
az storage blob update --connection-string $AZURE_BLOB_CONNECTION_STRING --container-name $CONTAINER_NAME --name $BLOB_NAME --content-cache $CONTENT_CACHE > /dev/null;
echo "$BLOB_NAME"
# If you don't have pv install, uncomment everything after done
done | cat | pv -pte --line-mode --size $NUMBER_OF_BLOBS > /dev/null
这可能为时已晚,但最近我想以不同的方式做同样的事情,我有图像列表,需要使用 powershell 脚本应用(当然在 Azure 存储程序集的帮助下)希望有人会发现这很有用在未来。
使用 powershell 脚本设置 Azure blob 缓存控制中给出的完整说明
Add-Type -Path "C:\Program Files\Microsoft SDKs\Windows Azure\.NET SDK\v2.3\ref\Microsoft.WindowsAzure.StorageClient.dll"
$accountName = "[azureaccountname]"
$accountKey = "[azureaccountkey]"
$blobContainerName = "images"
$storageCredentials = New-Object Microsoft.WindowsAzure.StorageCredentialsAccountAndKey -ArgumentList $accountName,$accountKey
$storageAccount = New-Object Microsoft.WindowsAzure.CloudStorageAccount -ArgumentList $storageCredentials,$true
#$blobClient = $storageAccount.CreateCloudBlobClient()
$blobClient = [Microsoft.WindowsAzure.StorageClient.CloudStorageAccountStorageClientExtensions]::CreateCloudBlobClient($storageAccount)
$cacheControlValue = "public, max-age=604800"
echo "Setting cache control: $cacheControlValue"
Get-Content "imagelist.txt" | foreach {
$blobName = "$blobContainerName/$_".Trim()
echo $blobName
$blob = $blobClient.GetBlobReference($blobName)
$blob.Properties.CacheControl = $cacheControlValue
$blob.SetProperties()
}
通过 PowerShell 脚本设置存储 blob 缓存控制属性
https://gallery.technet.microsoft.com/How-to-set-storage-blob-4774aca5
#creat CloudBlobClient
Add-Type -Path "C:\Program Files\Microsoft SDKs\Windows Azure\.NET SDK\v2.3\ref\Microsoft.WindowsAzure.StorageClient.dll"
$storageCredentials = New-Object Microsoft.WindowsAzure.StorageCredentialsAccountAndKey -ArgumentList $StorageName,$StorageKey
$blobClient = New-Object Microsoft.WindowsAzure.StorageClient.CloudBlobClient($BlobUri,$storageCredentials)
#set Properties and Metadata
$cacheControlValue = "public, max-age=60480"
foreach ($blob in $blobs)
{
#set Metadata
$blobRef = $blobClient.GetBlobReference($blob.Name)
$blobRef.Metadata.Add("abcd","abcd")
$blobRef.SetMetadata()
#set Properties
$blobRef.Properties.CacheControl = $cacheControlValue
$blobRef.SetProperties()
}