개발일기

SpringBoot AWS 설정하는 방법 본문

취준생 프로젝트

SpringBoot AWS 설정하는 방법

한둥둥 2024. 7. 16. 17:55

🔥 BuildGradle - 의존성 추가

// aws-bucket
    implementation 'io.awspring.cloud:spring-cloud-starter-aws:2.4.4'

    // 파일 업로드
    implementation 'commons-io:commons-io:2.14.0'
    implementation 'commons-fileupload:commons-fileupload:1.5'

 

 

🛠️ application.yml - aws  자격 증명 입력

 

cloud:
  aws:
    credentials:
      instance-profile: false
      accessKey: ${LOC_AWS_ACCESS_KEY}
      secretKey: ${LOC_AWS_SECRET_KEY}
    s3:
      bucket: ${LOC_AWS_BUCKET_NAME}
    region:
      auto: false
      static: ap-northeast-2
    stack: false

 

 

🤗 Bean 등록

package darkoverload.itzip.global.config.aws;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * S3 연결을 위한 Bean 등록
 */
@Configuration
public class AWSS3Config {
    @Value("${cloud.aws.credentials.accessKey")
    private String accessKey;

    @Value("${cloud.aws.credentials.secretKey}")
    private String secretKey;

    @Value("${cloud.aws.region.static}")
    private String region;

    @Bean
    public AmazonS3Client amazonS3Client() {
        AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);

        return (AmazonS3Client) AmazonS3ClientBuilder
                .standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withRegion(region)
                .build();
    }
}

 

 

🔥 AWSService.class

package darkoverload.itzip.infra.bucket.aws;

import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ObjectMetadata;
import darkoverload.itzip.image.domain.image;
import darkoverload.itzip.image.exception.CustomFileException;
import darkoverload.itzip.global.config.response.code.CommonExceptionCode;
import darkoverload.itzip.global.util.FileUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;

@Component
@RequiredArgsConstructor
public class AWSService {

    private final AmazonS3Client amazonS3;

    @Value("${cloud.s3.s3.bucket}")
    private String bucketName;

    @Value("${file.path}")
    private String filePath;

    public image upload(image image, InputStream inputStream) {

        String fileName = FileUtil.generateFileName(image.getFilename());
        amazonS3.putObject(bucketName, fileName, inputStream, getObjectMetadata(image));

        image in = null;
        try {
            String dirUrl = filePath + fileName;
            in = image.builder()
                    .filePath(dirUrl)
                    .filename(fileName)
                    .size(image.getSize())
                    .fileType(FileUtil.getMimeType(inputStream))
                    .contentType(image.getContentType())
                    .build();
        } catch (IOException e) {
            throw new CustomFileException(CommonExceptionCode.FILE_ERROR);
        }

        return in;
    }



    private ObjectMetadata getObjectMetadata(image image) {
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(image.getContentType());
        objectMetadata.setContentLength(image.getSize());

        return objectMetadata;
    }

}

 

 

아래 코드에서 fileName 을 만들어주었다. FileUtil에 있는 generateFileName을 통해서 파일 이름을 UUID로 스트링으로 바꿔서 내려줬다. 

 

amazonS3.putObject를 통해서 bucket을 실질적으로 이미지를 업로드 해주었다. 

String fileName = FileUtil.generateFileName(image.getFilename());
amazonS3.putObject(bucketName, fileName, inputStream, getObjectMetadata(image));

 

 

아래 코드는 dirUrl 같은 경우에는 cloudfront에 해당하는 https url로 이미지를 가져오기 위하여 설정해주었다. 

image in = null;
try {
     String dirUrl = filePath + fileName;
     in = image.builder()
               .filePath(dirUrl)
               .filename(fileName)
               .size(image.getSize())
               .fileType(FileUtil.getMimeType(inputStream))
               .contentType(image.getContentType())
               build();
        } catch (IOException e) {
            throw new CustomFileException(CommonExceptionCode.FILE_ERROR);
        }
 }