이 빠른 기사에서는 S3에 초점을 맞춰 Spring Cloud 플랫폼에서 제공되는 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. 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*.txt URL 은 my-s3-bucket 의 모든 폴더에서 이름이 ' a '로 시작하는 모든 텍스트 파일을 재귀적으로 찾습니다 .

Bean ResourceLoaderResourcePatternResolver 는 Spring Boot의 자동 구성 기능을 사용하여 애플리케이션 시작 시 생성됩니다.

4. 결론

그리고 끝났습니다. 이것은 Spring Cloud AWS를 사용하여 S3에 액세스하는 방법에 대한 빠르고 정확한 소개입니다.

시리즈 의 다음 기사에서는 프레임워크의 EC2 지원을 살펴보겠습니다.

평소와 같이 예제는 GitHub 에서 사용할 수 있습니다 .

다음 »
스프링 클라우드 AWS – EC2
Cloud footer banner