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”。
还有 withIfUnmodifiedSince() withIfModifiedSince() 方法,它们各自采用一个 Date 对象。

如果 etag 或 md5 不可用,则需要使用 GetObjectMetadataRequest 检索它。
一个有效的替代方法是,如果 Date 足够旧,则使用 withIfUnmodifiedSince()。 

带 ECS 技术支持的 SR

如果担心对象的存在,请向 ECS 支持团队提出服务请求。
 

Affected Products

Elastic Cloud Storage

Products

Elastic Cloud Storage
Article 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.