选项
首页首页 Skill 云基础设施 aws-sdk-java-v2-s3

提供了使用 AWS SDK for Java 2.x 的 Amazon S3 模式和示例。适用于处理 S3 存储桶、上传/下载对象、分段上传、预签名 URL、S3 Transfer Manager、对象操作或 S3 特定配置等场景。

...展开全部
23
更新时间 2026-08-24

关于aws-sdk-java-v2-s3

本技能是一份基于 AWS SDK for Java 2.x 精心整理的 Amazon S3 使用模式参考指南。 它解决了Java应用程序中正确使用S3对象存储时常遇到的问题:如何创建和管理存储桶、使用正确的请求构建器上传和下载对象、处理大文件、生成临时访问URL,以及将所有这些功能集成到Spring Boot应用程序中。 它不再让开发者从零散的文档中拼凑 SDK 的流畅构建器 API,而是提供了一系列可直接适用的代码片段,其中包含服务器端加密和存储类选择等合理的默认设置。

内容涵盖了对象生命周期的核心环节(使用等待器调用 createBucket、通过 RequestBody.fromFile 上传对象、按路径获取对象、批量删除对象),使用 S3Presigner 生成带有效期限制的预签名 URL,以及用于优化大文件传输的 S3 Transfer Manager。 参考文件深入探讨了客户端配置(包括重试策略)、对象操作、传输模式,以及多环境的 Spring Boot 集成,涵盖同步/异步客户端、响应式服务模板、支持元数据的上传、前缀列表和批量删除等功能。快速参考表将每项操作与其对应的 SDK 方法进行映射,并将存储类与其使用场景进行关联。

本书面向将 S3 集成到服务中的 Java 后端开发人员和云工程师,特别是需要面向生产环境的配置示例的 Spring Boot 团队。典型用例包括构建文件存储功能、迁移到 SDK v2、添加预签名 URL 共享以及优化大文件传输。 凭证通过标准提供商和外部环境变量进行管理,遵循常规的 AWS 实践。

常见问题

本文针对哪个版本的 AWS SDK?

AWS Java SDK 2.x。示例在 Maven 依赖项块中将 S3 和 s3-transfer-manager 构建产物固定为 2.20.0 版本。

是否涵盖大文件上传?

是的。文档中介绍了用于优化传输的 S3 Transfer Manager,并说明了针对大于 100MB 文件的多部分上传,同时提供了基于构建器的 UploadFileRequest 示例。

凭证如何处理?

通过标准的 AWS 凭证提供程序。Spring Boot 参考示例展示了由外部环境变量(AWS_ACCESS_KEY / AWS_SECRET_KEY)驱动的 StaticCredentialsProvider,这些变量存储在特定配置文件的属性文件中,这属于常规配置方式,而非将机密信息嵌入代码中。

我可以将它与 Spring Boot 配合使用吗?

可以。专门的参考文档涵盖了多环境配置、用于同步/异步/传输管理器/预签名客户端的条件 Bean,以及一个响应式的 S3Service 模板。

预签名 URL 的最大过期时间是多少?

快速参考指南中指出预签名 URL 的最长有效期为 7 天;示例中使用的签名有效期为 10 分钟。

所有文件

5个文件references/s3-spring-boot-integration.md20.7KB查看references/s3-object-operations.md10.4KB查看references/s3-transfer-patterns.md14.6KB 查看 references/s3-client-setup.md 5.3KB 查看 SKILL.md 9.3 KB 查看
在 GitHub 上查看

Overview

Provides patterns for S3 operations: bucket management, object upload/download with multipart support, presigned URLs, S3 Transfer Manager, and S3-specific configurations using AWS SDK for Java 2.x.

When to Use

  • Creating, listing, or deleting S3 buckets with proper configuration
  • Uploading or downloading objects from S3 with metadata and encryption
  • Working with multipart uploads for large files (>100MB) with error handling
  • Generating presigned URLs for temporary access to S3 objects
  • Copying or moving objects between S3 buckets with metadata preservation
  • Setting object metadata, storage classes, and access controls
  • Implementing S3 Transfer Manager for optimized file transfers
  • Integrating S3 with Spring Boot applications for cloud storage

Quick Reference

OperationMethodNotes
Create bucketcreateBucket()Wait with waiter().waitUntilBucketExists()
Upload objectputObject()Use RequestBody.fromFile()
Download objectgetObject()Streams to file or memory
Delete objectsdeleteObjects()Batch up to 1000 keys
Presigned URLpresigner.presignGetObject()Max 7 days expiration

Storage Classes

ClassUse Case
STANDARDFrequently accessed data
STANDARD_IAInfrequently accessed data
GLACIERLong-term archive
INTELLIGENT_TIERINGAutomatic cost optimization

Instructions

1. Add Dependencies

<dependency>    <groupId>software.amazon.awssdk</groupId>    <artifactId>s3</artifactId>    <version>2.20.0</version></dependency><dependency>    <groupId>software.amazon.awssdk</groupId>    <artifactId>s3-transfer-manager</artifactId>    <version>2.20.0</version></dependency>

2. Create S3 Client

S3Client s3Client = S3Client.builder()    .region(Region.US_EAST_1)    .build();// With retry logicS3Client s3Client = S3Client.builder()    .region(Region.US_EAST_1)    .overrideConfiguration(b -> b        .retryPolicy(RetryPolicy.builder()            .numRetries(3)            .build()))    .build();

3. Create Bucket

CreateBucketRequest request = CreateBucketRequest.builder()    .bucket(bucketName)    .build();s3Client.createBucket(request);// Wait until readys3Client.waiter().waitUntilBucketExists(    HeadBucketRequest.builder().bucket(bucketName).build());

4. Upload Object

PutObjectRequest request = PutObjectRequest.builder()    .bucket(bucketName)    .key(key)    .contentType("application/pdf")    .serverSideEncryption(ServerSideEncryption.AES256)    .storageClass(StorageClass.STANDARD_IA)    .build();s3Client.putObject(request, RequestBody.fromFile(Paths.get(filePath)));// Validate upload completionHeadObjectResponse headResp = s3Client.headObject(HeadObjectRequest.builder()    .bucket(bucketName)    .key(key)    .build());

5. Download Object

GetObjectRequest request = GetObjectRequest.builder()    .bucket(bucketName)    .key(key)    .build();s3Client.getObject(request, Paths.get(destPath));

6. Generate Presigned URL

try (S3Presigner presigner = S3Presigner.create()) {    GetObjectRequest getRequest = GetObjectRequest.builder()        .bucket(bucketName)        .key(key)        .build();    GetObjectPresignRequest presignRequest = GetObjectPresignRequest.builder()        .signatureDuration(Duration.ofMinutes(10))        .getObjectRequest(getRequest)        .build();    String url = presigner.presignGetObject(presignRequest).url().toString();}

7. Use Transfer Manager (Large Files)

try (S3TransferManager tm = S3TransferManager.create()) {    UploadFileRequest request = UploadFileRequest.builder()        .putObjectRequest(req -> req.bucket(bucketName).key(key))        .source(Paths.get(filePath))        .build();    FileUpload upload = tm.uploadFile(request);    CompletedFileUpload result = upload.completionFuture().join();}

Best Practices

Performance

  • Use S3 Transfer Manager: Automatic multipart uploads for files >100MB
  • Reuse S3 Client: Clients are thread-safe; reuse throughout application
  • Enable async operations: Use S3AsyncClient for I/O-bound operations
  • Configure timeouts: Set appropriate timeouts for large file operations

Security

  • Use temporary credentials: IAM roles or AWS STS for short-lived tokens
  • Enable encryption: Use AES-256 or AWS KMS for sensitive data
  • Use presigned URLs: Avoid exposing credentials with temporary access
  • Validate metadata: Sanitize user-provided metadata

Error Handling

  • Implement retry logic: Exponential backoff for network operations
  • Handle throttling: Proper handling of 429 responses
  • Clean up failures: Abort failed multipart uploads

Cost Optimization

  • Use appropriate storage classes: STANDARD, STANDARD_IA, INTELLIGENT_TIERING
  • Implement lifecycle policies: Automatic transition/expiration
  • Minimize API calls: Use batch operations when possible

Constraints and Warnings

  • Object Size: Single PUT limited to 5GB; use multipart for larger files
  • Bucket Names: Must be globally unique across all AWS accounts
  • Object Immutability: Objects cannot be modified; must be replaced entirely
  • Eventual Consistency: List operations may have slight delays after uploads
  • Presigned URLs: Maximum expiration time is 7 days
  • Multipart Uploads: Parts must be at least 5MB except last part

Examples

Complete Upload Workflow with Validation

// 1. Upload with validationPutObjectRequest putRequest = PutObjectRequest.builder()    .bucket(bucketName)    .key(key)    .contentType(contentType)    .build();s3Client.putObject(putRequest, RequestBody.fromFile(Paths.get(filePath)));// 2. Validate with headObjectHeadObjectResponse headResp = s3Client.headObject(HeadObjectRequest.builder()    .bucket(bucketName)    .key(key)    .build());// 3. Verify metadatalong fileSize = Files.size(Paths.get(filePath));if (headResp.contentLength() != fileSize) {    throw new IllegalStateException("Upload size mismatch");}

Multipart Upload with Abort-on-Failure

// 1. Initiate multipart uploadCreateMultipartUploadRequest createRequest = CreateMultipartUploadRequest.builder()    .bucket(bucketName)    .key(key)    .build();CreateMultipartUploadResponse multipartUpload = s3Client.createMultipartUpload(createRequest);String uploadId = multipartUpload.uploadId();try {    // 2. Upload parts    List<CompletedPart> parts = new ArrayList<>();    int partNumber = 1;    byte[] fileBytes = Files.readAllBytes(Paths.get(filePath));    int chunkSize = 5 * 1024 * 1024; // 5MB minimum    for (int offset = 0; offset < fileBytes.length; offset += chunkSize) {        int length = Math.min(chunkSize, fileBytes.length - offset);        UploadPartRequest uploadPartRequest = UploadPartRequest.builder()            .bucket(bucketName)            .key(key)            .uploadId(uploadId)            .partNumber(partNumber)            .build();        UploadPartResponse partResponse = s3Client.uploadPart(uploadPartRequest,            RequestBody.fromBytes(Arrays.copyOfRange(fileBytes, offset, offset + length)));        parts.add(CompletedPart.builder()            .partNumber(partNumber)            .eTag(partResponse.eTag())            .build());        partNumber++;    }    // 3. Complete multipart upload    CompleteMultipartUploadRequest completeRequest = CompleteMultipartUploadRequest.builder()        .bucket(bucketName)        .key(key)        .uploadId(uploadId)        .multipartUpload(CompletedMultipartUpload.builder().parts(parts).build())        .build();    s3Client.completeMultipartUpload(completeRequest);} catch (Exception e) {    // 4. Abort on failure    AbortMultipartUploadRequest abortRequest = AbortMultipartUploadRequest.builder()        .bucket(bucketName)        .key(key)        .uploadId(uploadId)        .build();    s3Client.abortMultipartUpload(abortRequest);    throw new RuntimeException("Upload failed, cleanup performed", e);}

References

  • references/s3-client-setup.md — Client configuration and basic operations
  • references/s3-object-operations.md — Advanced object operations
  • references/s3-transfer-patterns.md — Transfer Manager and multipart uploads
  • references/s3-spring-boot-integration.md — Spring Boot integration patterns
  • AWS S3 Developer Guide
  • AWS SDK for Java 2.x S3 API

Related Skills

  • aws-sdk-java-v2-core - Core AWS SDK patterns and configuration
  • spring-boot-dependency-injection - Spring dependency injection patterns

所有文件

0 个文件

安装 aws-sdk-java-v2-s3

下载技能文件并将其解压到 .claude/skills/ 目录中。

下载ZIP

克隆仓库并复制技能文件到您的项目中。

git clone https://github.com/giuseppe-trisciuoglio/developer-kit/blob/main/plugins/developer-kit-java/skills/aws-sdk-java-v2-s3/SKILL.md # Copy SKILL.md to your .claude/skills/ directory

复制 复制
快速设置: 将技能文件夹复制到 .claude/skills/ 目录下,Claude 会自动检测并使用该技能。

相关技能

Cloudflare Manager
更新时间 2026-06-29
pinecone
更新时间 2026-06-29
azure-setup-guide
更新时间 2026-06-29
sentry-architecture-variants
更新时间 2026-06-29
OR