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

时间:2020-10-19 08:30:16

标签: java azure azure-blob-storage azure-java-sdk

我正在使用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'

1 个答案:

答案 0 :(得分:0)

根据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'