選項
首頁首頁 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 物件儲存時常見的問題提供解決方案:如何建立與管理儲存桶、使用正確的請求建構器上傳與下載物件、處理大型檔案、產生臨時存取網址,並將所有這些功能整合至 Spring Boot 應用程式中。 與其讓開發人員從零散的文件中拼湊 SDK 的流暢建構器 API,本技能提供可直接套用的程式碼片段,並設定了合理的預設值,例如伺服器端加密與儲存類別選取。

內容涵蓋核心物件生命週期(使用等待器呼叫 `createBucket`、透過 `RequestBody.fromFile` 傳入 `putObject`、根據路徑取得 `getObject`,以及批次刪除 `deleteObjects`)、使用 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