이 글에서는 Spring Boot 애플리케이션이 AWS S3와 연결하여 파일을 업로드하는 방법을 소개합니다. AWS 자격 증명과 설정을 env.properties에 저장하고, 이 설정을 이용해 S3에 안전하게 접근할 수 있도록 S3Util과 S3Service 클래스를 구현했습니다.
■ env.properties 설정 파일
env.properties 파일은 AWS S3와 연결할 때 필요한 다양한 설정 값을 포함하고 있습니다. 다음과 같은 설정이 필요합니다.
env.aws.accessKey=sample
env.aws.secretKey=sample
env.aws.region=sample
env.aws.bucket=sample
env.aws.endpoint=http://sample or https://sample.com
- env.aws.accessKey: AWS 접근 키로, S3와 같은 AWS 서비스에 접근할 수 있는 권한을 부여하는 데 필요합니다.
- env.aws.secretKey: AWS 비밀 키로, 접근 키와 함께 S3에 인증할 때 사용됩니다.
- env.aws.region: S3 버킷이 위치한 리전입니다. 예를 들어, 서울 리전은 ap-northeast-2입니다.
- env.aws.bucket: S3 버킷 이름입니다. 업로드할 파일이 저장될 S3 버킷을 지정합니다.
- env.aws.endpoint: S3와의 연결 엔드포인트입니다. 일반적으로 HTTPS로 설정하지만, 이 예제에서는 HTTP 프로토콜을 사용할 수도 있습니다.
■ S3Util.java: S3 클라이언트 생성
S3Util 클래스는 Spring의 @Configuration 어노테이션을 사용하여 스프링 컨테이너에 등록되는 구성 클래스입니다. 이 클래스는 AWS 자격 증명과 S3 엔드포인트를 설정하여 AmazonS3 객체를 생성하고, 이 객체를 다른 클래스에서 사용할 수 있도록 @Bean으로 등록합니다.
@Configuration
public class S3Util {
@Value("${env.aws.accessKey}")
private String accessKey;
@Value("${env.aws.secretKey}")
private String secretKey;
@Value("${env.aws.region}")
private String region;
@Value("${env.aws.endpoint}")
private String endpoint;
// AWS 자격 증명과 리전을 설정하는 S3Client 생성
@Bean
public AmazonS3 amazonS3() {
AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
return AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpoint, region))
.enablePathStyleAccess() // Path 스타일 사용을 위해 설정
.build();
}
}
- @Configuration: 이 어노테이션을 통해 S3Util 클래스는 스프링 설정 클래스로 등록됩니다.
- @Bean: amazonS3() 메서드를 통해 AmazonS3 객체를 스프링 빈으로 등록하여 다른 클래스에서 @Autowired로 주입받을 수 있습니다.
- withEndpointConfiguration(): 커스텀 엔드포인트를 설정하여 S3와 연결할 때 사용합니다. 이 엔드포인트는 기본 HTTPS 연결뿐 아니라, HTTP 연결도 가능합니다.
- enablePathStyleAccess(): VPC 엔드포인트를 사용할 때 필수인 Path 스타일을 강제로 설정합니다.
■ S3Service 클래스: 파일 업로드 로직
S3Service 클래스는 실제 파일 업로드 로직을 포함하고 있습니다. @Autowired를 통해 AmazonS3 클라이언트를 주입받아 사용합니다. 이를 통해 S3Util 클래스에서 생성한 AmazonS3 객체가 스프링 컨테이너에 등록되고, S3Service 클래스에서 이를 바로 사용할 수 있습니다.
public class S3Service {
@Value("${env.aws.bucket}")
private String bucket;
@Autowired
private AmazonS3 s3Client;
public int uploadFile(HashMap<String, Object> params, MultipartHttpServletRequest request) {
try {
Iterator<String> itr = request.getFileNames();
while (itr.hasNext()) {
MultipartFile file = request.getFile(itr.next());
String fileName = "cm.pdf"; // 업로드할 파일 이름 설정
InputStream inputStream = file.getInputStream();
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(file.getSize());
objectMetadata.setContentType(file.getContentType());
// S3 버킷에 파일 업로드
s3Client.putObject(new PutObjectRequest(bucket, fileName, inputStream, objectMetadata));
}
return 1;
} catch (AmazonServiceException e) {
log.info("Amazon service error :: " + e.getMessage());
} catch (IOException e) {
log.info("IO error :: " + e.getMessage());
}
return 0;
}
}
- @Autowired: AmazonS3 객체를 S3Service 클래스에 주입하여 S3와의 연결을 설정 파일에서 직접 가져옵니다.
- putObject(): 지정된 버킷에 파일을 업로드합니다. 파일 메타데이터(파일 크기와 유형)를 설정하여 업로드합니다.
■ 엔드포인트 URL 설정 및 SSL 옵션
엔드포인트 URL(env.aws.endpoint)은 S3 버킷과 연결할 때 사용하는 URL입니다. 일반적으로 AWS S3는 보안을 위해 HTTPS를 사용하여 데이터를 암호화합니다. 그러나 테스트 목적 또는 내부 네트워크에서의 사용을 위해 HTTP로 엔드포인트를 설정할 수 있습니다.
- HTTP 프로토콜은 데이터를 암호화하지 않기 때문에, 프로덕션 환경에서는 HTTPS를 사용하는 것이 필수적입니다.
'Java' 카테고리의 다른 글
| [Redis] 캐싱 구현(콜론 두 개 :: 등장 이유) (0) | 2025.01.30 |
|---|---|
| [WebSocket] Java로 WebSocket 구현하기(feat. JWT) (0) | 2025.01.23 |
| [Gradle] 의존성 설정과 컴파일/런타임 시점의 이해(feat.Lombok) (0) | 2024.09.30 |
| [Gradle] 의존성 설정 알아보기 (1) | 2024.09.27 |
| [JUnit]Spring Boot에서 JUnit으로 테스트하는 방법 (1) | 2024.09.09 |