使用服务帐户从Azure Blob存储中批量删除文件

问题描述

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

我有一个Azure Blob存储服务帐户(client_id和client_secret)。我已经使用CloudBlobClient创建了StorageCredentialsToken,如下所示:

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文档,该文档表示我们可以使用BlobBatchClient删除多个文件。在文档中,我找不到使用服务帐户(使用由client_id和client_secret获得的访问令牌)创建BlobBatchClient的任何方法。

是否可以删除异步调用中的文件,因为我需要删除100多个文件? 还有其他批量删除文件的解决方案吗?

SDK版本compile group: 'com.microsoft.azure',name: 'azure-storage',version: '8.6.5'

解决方法

根据Jim的评论,我已经使用访问令牌创建了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());
                }
        );
}

等级依赖性:

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'

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...