azure 从容器内的子文件夹中删除Blob

omtl5h9j  于 2023-08-07  发布在  其他
关注(0)|答案(1)|浏览(101)

我试图从blob存储中删除一些blob,但最初不知道要删除哪些blob。基本上,我想列出blob并找出最近的一个并删除该一个。我的代码看起来像这样:

private void deleteLatestBlob(String sasUrl, String container)
{
    BlobServiceClient serviceClient = new BlobServiceClientBuilder().endpoint(sasUrl).buildClient();
    BlobContainerClient container = serviceClient.getBlobContainerClient(container);
    List<BlobClient> clients = container.listBlobsByHierarchy("foo/bar/")
        .stream()
        .map(item -> container.getBlobClient(item.getName()))
        .sorted((client1, client2) ->
            client2.getProperties().getLastModified()
                .compareTo(client1.getProperties().getLastModified()))
        .collect(Collectors.toList());

    if (!clients.isEmpty())
    {
        clients.get(clients.size() - 1).delete(); // Exception happens here
    }
}

字符串
这里的目标是删除foo/bar/中最近的blob。但是,我得到一个异常,消息是“请求的URI不代表服务器上的任何资源”。为了避免垃圾邮件,下面是堆栈跟踪的一个片段:

com.azure.storage.blob.models.BlobStorageException: Status code 400, "?<?xml version="1.0" encoding="utf-8"?><Error><Code>InvalidUri</Code><Message>The requested URI does not represent any resource on the server.
RequestId:300025de-001e-006e-7644-bfb34b000000
Time:2023-07-25T22:09:35.6134376Z</Message></Error>"
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
        at com.azure.core.http.rest.RestProxy.instantiateUnexpectedException(RestProxy.java:370)
        at com.azure.core.http.rest.RestProxy.lambda$ensureExpectedStatus$7(RestProxy.java:425)
        at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:125)
... snip...
        Suppressed: java.lang.Exception: #block terminated with an error
                at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:99)
                at reactor.core.publisher.Mono.block(Mono.java:1706)
                at com.azure.storage.common.implementation.StorageImplUtils.blockWithOptionalTimeout(StorageImplUtils.java:128)
                at com.azure.storage.blob.specialized.BlobClientBase.deleteWithResponse(BlobClientBase.java:973)
                at com.azure.storage.blob.specialized.BlobClientBase.delete(BlobClientBase.java:944)


如果我使用的blob名称直接来自刚刚从清单中获得的BlobItem,那么资源怎么会丢失呢?

kq0g1dla

kq0g1dla1#

当您使用listBlobsByHierarchy列出blob时,它将返回blob和虚拟文件夹。我的猜测是,列表中的第一个项目是一个虚拟文件夹,因为它不是一个实际的blob,删除操作失败,出现404 (NotFound)错误。
您可以通过检查isPrefix()来检查返回的blob是否是实际的blob来过滤列表,或者您可以使用flat listing来返回blob列表(没有虚拟文件夹)。

相关问题