gpt4 book ai didi

java - 使用服务帐户从azure blob存储中批量删除文件

转载 作者:行者123 更新时间:2023-12-03 00:23:14 28 4
gpt4 key购买 nike

我正在使用 azure blob 存储来存储我的项目文件。

我有一个 azure blob storage 的服务帐户(client_id 和 client_secret)。我使用 StorageCredentialsToken 创建了 CloudBlobClient,如下所示:

StorageCredentialsToken credentialsToken = new StorageCredentialsToken("account name", "access token generated uing client_id and client_secret");
CloudBlobClient blobClient = new CloudBlobClient(new URI("https://accountname.blob.core.windows.net/"), credentialsToken);
CloudBlobContainer cloudBlobContainer = blobClient.getContainerReference("conteiner name");

现在使用 CloudBlobContainer 我可以一次删除一个文件:

CloudBlockBlob blockBlobReference = cloudBlobContainer.getBlockBlobReference(key);
if (blockBlobReference.exists()) {
blockBlobReference.delete();
}

如何使用一次调用删除多个文件?

我找到this doc 中说我们可以使用 BlobBatchClient 删除多个文件。在文档中,我找不到任何使用服务帐户(使用通过 client_id 和 client_secret 获取的访问 token )创建 BlobBatchClient 的方法。

我们可以在异步调用中删除文件吗,因为我需要删除 100 个文件?有其他解决方案来批量删除文件吗?

SDK版本编译组:'com.microsoft.azure',名称:'azure-storage',版本:'8.6.5'

最佳答案

根据 Jim 的评论,我使用访问 token 创建了 BlobServiceAsyncClient示例方法:

public void delete(List<String> files) {
String endpoint = "https://azureaccount.blob.core.windows.net/";
AccessToken accessToken = new AccessToken("access token created with client id and client secret", OffsetDateTime.now().plusHours(1));
BlobServiceAsyncClient storageClient = new BlobServiceClientBuilder().credential(request -> Mono.just(accessToken))
.endpoint(endpoint)
.buildAsyncClient();
BlobBatchClient blobBatchClient = new BlobBatchClientBuilder(storageClient).buildClient();
List<String> blobUrls = new ArrayList<>();
files.forEach(name -> {
try {
String blobUrl = endpoint + "conteinerName/" + URLEncoder.encode(name, "UTF-8");
blobUrls.add(blobUrl);
} catch (UnsupportedEncodingException e) {
LOGGER.debug("Can not encode blob name={}", name);
}
});
blobBatchClient.deleteBlobs(blobUrls, DeleteSnapshotsOptionType.INCLUDE).forEach(response -> {
LOGGER.debug("File with name={} deleted, status code={}", response.getRequest().getUrl(), response.getStatusCode());
}
);
}

Gradle 依赖项:

compile group: 'com.azure', name: 'azure-storage-blob', version: '12.0.0'
compile group: 'com.azure', name: 'azure-storage-blob-batch', version: '12.6.0'

关于java - 使用服务帐户从azure blob存储中批量删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64423714/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com