1. 简单的 S3 文件下载

直接访问 S3 上的文件非常简单,Spring Cloud AWS 已经帮我们封装好了底层细节:

@Autowired
ResourceLoader resourceLoader;

public void downloadS3Object(String s3Url) throws IOException {
    Resource resource = resourceLoader.getResource(s3Url);
    File downloadedS3Object = new File(resource.getFilename());
 
    try (InputStream inputStream = resource.getInputStream()) {
        Files.copy(inputStream, downloadedS3Object.toPath(), 
          StandardCopyOption.REPLACE_EXISTING);
    }
}

✅ 核心要点:

  • 通过 ResourceLoader 自动注入获取 S3 资源
  • 使用标准 Java IO 流处理文件下载
  • 自动处理文件覆盖逻辑(REPLACE_EXISTING

⚠️ 注意:确保 AWS 凭证已正确配置,否则会抛出 AmazonS3Exception

2. 简单的 S3 文件上传

上传文件同样简单粗暴,直接使用 WritableResource 接口:

public void uploadFileToS3(File file, String s3Url) throws IOException {
    WritableResource resource = (WritableResource) resourceLoader
      .getResource(s3Url);
 
    try (OutputStream outputStream = resource.getOutputStream()) {
        Files.copy(file.toPath(), outputStream);
    }
}

踩坑提醒:

  • 必须显式转换为 WritableResource 才能获取输出流
  • 上传大文件时注意内存占用,建议使用分块上传(本文未展示)
  • 确保目标 bucket 有写入权限

3. S3 URL 结构详解

S3 URL 采用标准格式,理解这个结构很重要:

s3://<bucket>/<object>

举个实际例子:

  • bucket 名称:my-s3-bucket
  • 文件路径:foo/bar.zip
  • 完整 URL:s3://my-s3-bucket/foo/bar.zip

3.1 批量文件操作

需要下载多个文件?使用 ResourcePatternResolver 配合 Ant 风格通配符:

private ResourcePatternResolver resourcePatternResolver;
 
@Autowired
public void setupResolver(ApplicationContext applicationContext, AmazonS3 amazonS3) {
    this.resourcePatternResolver = 
      new PathMatchingSimpleStorageResourcePatternResolver(amazonS3, applicationContext);
 }

public void downloadMultipleS3Objects(String s3Url) throws IOException {
    Resource[] allFileMatchingPatten = this.resourcePatternResolver
      .getResources(s3Url);
        // 批量处理逻辑...
    }
}

通配符使用技巧:

  • s3://my-s3-bucket/**/*.txt → 递归匹配所有 txt 文件
  • s3://my-s3-bucket/foo/a*.zip → 匹配 foo 目录下以 a 开头的 zip 文件
  • s3://my-s3-bucket/????.log → 匹配 4 字符命名的日志文件

⚠️ 性能提示:通配符查询会触发 S3 的 ListObjects 操作,大 bucket 下慎用深度递归(**

3.2 自动配置原理

Spring Boot 的自动配置机制会自动创建:

  • ResourceLoader bean
  • ResourcePatternResolver bean

无需手动配置,开箱即用。

4. 总结

Spring Cloud AWS 对 S3 的封装确实简洁高效,几行代码就能搞定文件操作。核心优势:

  • 统一资源抽象(Resource 接口)
  • 无缝集成 Spring 生态
  • 自动处理 AWS 认证和连接管理

下一篇我们将深入探讨 EC2 集成,敬请期待。完整示例代码已上传至 GitHub 仓库


原始标题:Spring Cloud AWS – S3