SpringCloudAWS–S3
このクイック記事では、Spring Cloudプラットフォームで提供されるAWSサポートについて、S3に焦点を当てて説明します。
1. シンプルな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. シンプルなS3アップロード
ファイルをアップロードすることもできます。
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構造
s3Url は、次の形式を使用して表されます。
s3://<bucket>/<object>
たとえば、ファイルbar.zipがmy-s3-bucketバケットのfooフォルダーにある場合、URLは次のようになります。
s3://my-s3-bucket/foo/bar.zip
また、 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);
// ...
}
}
URLには、正確な名前の代わりにワイルドカードを含めることができます。
たとえば、 s3:// my-s3-bucket / ** /a*。txtURLは、任意のフォルダで名前が「a」で始まるすべてのテキストファイルを再帰的に検索します。 my-s3-bucketの。
Bean ResourceLoaderおよびResourcePatternResolverは、アプリケーションの起動時にSpring Bootの自動構成機能を使用して作成されることに注意してください。
4. 結論
これで完了です。これは、Spring CloudAWSを使用してS3にアクセスするための簡単で的確な紹介です。
シリーズの次の記事では、フレームワークのEC2サポートについて説明します。
いつものように、例はGitHubでから入手できます。