Spring Cloud AWS - S3

Spring Cloud AWS – S3

この簡単な記事では、S3に焦点を当ててSpringCloudプラットフォームで提供されるAWSサポートについて説明します。

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. S3URL構造

s3Urlは、次の形式で表されます。

s3:///


たとえば、ファイルbar.zipmy-s3-bucketバケットのフォルダfooにある場合、URLは次のようになります。

s3://my-s3-bucket/foo/bar.zip

また、ResourcePatternResolverとAntスタイルのパターンマッチングを使用して、一度に複数のオブジェクトをダウンロードすることもできます。

@Autowired
ResourcePatternResolver resourcePatternResolver;

public void downloadMultipleS3Objects(String s3Url) throws IOException {
    Resource[] allFileMatchingPatten = this.resourcePatternResolver
      .getResources(s3Url);
        // ...
    }
}

URLには、正確な名前の代わりにワイルドカードを含めることができます。

たとえば、s3://my-s3-bucket/*/a.txt URLは、my-s3-bucketの任意のフォルダで、名前が「a」で始まるすべてのテキストファイルを再帰的に検索します。

BeanResourceLoaderResourcePatternResolverは、アプリケーションの起動時にSpringBootの自動構成機能を使用して作成されることに注意してください。

4. 結論

これで完了です。これは、Spring CloudAWSを使用してS3にアクセスするための簡単で的確な紹介です。

next article of the seriesでは、フレームワークのEC2サポートについて説明します。

いつものように、例は利用可能なover on GitHubです。