In this quick article, we’re going to explore the AWS support provided in the Spring Cloud platform – focusing on S3.
在这篇快速文章中,我们将探讨Spring Cloud平台中提供的AWS支持–重点是S3。
1. Simple S3 Download
1.简单的S3下载
Let’s start by easily accessing files stored on S3:
让我们从轻松访问存储在S3上的文件开始。
@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);
}
}
2. Simple S3 Upload
2.简单的S3上传
We can also upload files:
我们也可以上传文件。
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);
}
}
3. S3 URL Structure
3.S3的URL结构
The s3Url is represented using the format:
s3Url使用格式表示。
s3://<bucket>/<object>
For example, if a file bar.zip is in the folder foo on a my-s3-bucket bucket, then the URL will be:
例如,如果一个文件bar.zip在foo文件夹中的my-s3-bucket桶中,那么URL将是。
s3://my-s3-bucket/foo/bar.zip
And, we can also download multiple objects at once using ResourcePatternResolver and the Ant-style pattern matching:
而且,我们还可以使用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);
// ...
}
}
URLs can contain wildcards instead of exact names.
URL可以包含通配符,而不是精确的名称。
For example the s3://my-s3-bucket/**/a*.txt URL will recursively look for all text files whose name starts with ‘a‘ in any folder of the my-s3-bucket.
例如,s3://my-s3-bucket/**/a*.txt URL将递归地寻找my-s3-bucket的任何文件夹中名称以”a“开头的所有文本文件。
Note that the beans ResourceLoader and ResourcePatternResolver are created at application startup using Spring Boot’s auto-configuration feature.
请注意,Bean ResourceLoader和ResourcePatternResolver是在应用程序启动时使用Spring Boot的自动配置功能创建的。
4. Conclusion
4.结论
And we’re done – this is a quick and to-the-point introduction to accessing S3 with Spring Cloud AWS.
我们就完成了–这是对用Spring Cloud AWS访问S3的一个快速和直接的介绍。
In the next article of the series, we’ll explore the EC2 support of the framework.
在系列的下一篇文章中,我们将探讨该框架的EC2支持。
As usual, the examples are available over on GitHub.
像往常一样,这些例子可以在GitHub上找到over。