ECS:檢查 S3 物件是否存在
Summary: 如何檢查物件是否存在於 s3 中。
This article applies to
This article does not apply to
This article is not tied to any specific product.
Not all product versions are identified in this article.
Instructions
使用 HEAD 更高效地檢查物件是否存在。
物件清單是檢查特定物件是否存在的一種本質上效率低下的方法。對於此特定請求,索引搜索不僅相對較慢,而且還會影響整體負載和性能。
請求特定對象始終比請求一個或多個與參數匹配的物件更有效。物件清單是一種必須查詢分散式索引的搜索形式。
對物件使用HEAD是檢查其是否存在的最佳方法。使用 ECS 物件 SDK,這是透過 GetObjectMetadataRequest 完成。
如果物件不存在,SDK 會由於 404 錯誤回應而引發以下異常:
Exception in thread "main" com.emc.object.s3.S3Exception: Not Found
以下是在 getObjectMetadata 用戶端方法中使用的 GetObjectMetadataRequest 的範例:
try { GetObjectMetadataRequest gom = new GetObjectMetadataRequest(<bucket>, <key>); S3ObjectMetadata om = s3.getObjectMetadata(gom); System.out.println("etag: " + om.getETag()); System.out.println("last modified: " + om.getLastModified().toString()); } catch(com.emc.object.s3.S3Exception e) { System.out.println("What happened: " + e.getMessage()); }
如果使用 AWS java 開發工具包,但物件不存在,開發工具包將引發以下異常。
com.amazonaws.services.s3.model.AmazonS3Exception: Not Found
下面是它的一個例子:
try { GetObjectMetadataRequest gom = new GetObjectMetadataRequest(AWSS3Factory.S3_BUCKET, key); s3.getObjectMetadata(gom); } catch(com.amazonaws.services.s3.model.AmazonS3Exception e) { System.out.println("What happened: " + e.getMessage()); }
檢查物件是否存在,以判斷是否需要 putObject。
如果檢查物件是否存在以確定是否需要 putObject,請考慮使用 PutObjectRequests 條件方法:
withIfMatch() and withIfNoneMatch().
這兩種方法都需要一個物件 etag 值,並在 PUT 請求中使用標頭“if-match”、“if-none-match”。
還有 IfUnmodifiedSince() 和 withIfModifiedSince() 的方法,每個方法都採用一個 Date 物件。
如果 etag 或 md5 無法使用,則需要使用 GetObjectMetadataRequest 來擷取。
一個有效的替代方案是使用 withIfUnmodifiedSince() 如果日期足夠舊。
SR 與 ECS 技術支援
如果對物件是否存在有疑慮,請向 ECS 支援小組開立服務要求。
Affected Products
Elastic Cloud StorageProducts
Elastic Cloud StorageArticle Properties
Article Number: 000014759
Article Type: How To
Last Modified: 22 May 2025
Version: 4
Find answers to your questions from other Dell users
Support Services
Check if your device is covered by Support Services.