公司最近用minio 生产环境也使用支持S3协议的存储服务。spring cloud aws 就支持S3协议。
- 第一步引入相关jar包
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-aws-dependencies</artifactId>
<version>2.3.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-starter-aws</artifactId>
</dependency>
- 添加配置文件
cloud:
aws:
credentials:
access-key: xxxxx
secret-key:xxxxx
s3:
endpoint: http://xxxxx
- 下载文件
可以通过使用s3协议引用 Amazon S3 存储桶和存储桶内的对象来下载文件。典型的模式是s3:///,bucket 是全局唯一的bucket 名称,object 是bucket 内的有效对象名称。对象名称可以是存储桶根文件夹中的文件,也可以是存储桶内目录中的嵌套文件。
下一个示例演示如何使用资源加载器加载不同的资源。
public class SimpleResourceLoadingBean {
@Autowired
private ResourceLoader resourceLoader;
public void resourceLoadingMethod() throws IOException {
Resource resource = this.resourceLoader.getResource("s3://myBucket/rootFile.log");
Resource secondResource = this.resourceLoader.getResource("s3://myBucket/rootFolder/subFile");
InputStream inputStream = resource.getInputStream();
//read file
}
}
4.上传文件
从 Spring Framework 3.1 开始,资源加载器也可以用来上传带有org.springframework.core.io.WritableResource 接口的文件,这是接口的特殊化org.springframework.core.io.ResourceLoader。客户端可以使用该WritableResource界面上传文件。下一个示例演示使用资源加载器上传资源。
public class SimpleResourceLoadingBean {
@Autowired
private ResourceLoader resourceLoader;
public void writeResource() throws IOException {
Resource resource = this.resourceLoader.getResource("s3://myBucket/rootFile.log");
WritableResource writableResource = (WritableResource) resource;
try (OutputStream outputStream = writableResource.getOutputStream()) {
outputStream.write("test".getBytes());
}
}
}
- 使用 TransferManager 上传
Amazon SDK 还提供了一个对上传文件非常有用的高级抽象,还提供了使用多部分功能的多线程。com.amazonaws.services.s3.transfer.TransferManager可以在应用程序代码中轻松创建A并注入com.amazonaws.services.s3.AmazonS3已使用 Spring Cloud AWS 资源加载器配置创建的预配置客户端。
此示例显示transferManager在应用程序中使用 来从硬盘驱动器上传文件。
public class SimpleResourceUploadingBean {
@Autowired
private AmazonS3 amazonS3;
public void withTransferManager() {
TransferManager transferManager = TransferManagerBuilder.standard()
.withS3Client(this.amazonS3)
.build();
transferManager.upload("myBucket","filename",new File("someFile"));
}
}
- 获取外网下载地址
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName,ossPath).withMethod(HttpMethod.Get).withExpiration(过期时间);
String url = amazonS3.generatePresignedUrl(request)+"";