GDSC 1차프로젝트(2) - S3 사용환경 설정

chaejm55·2023년 8월 31일
1

GDSC-KNU-2nd-Backend

목록 보기
8/10

GDSC 1차 프로젝트(네컷앨범 고도화) 두 번째 게시물입니다.

앞서 포스팅한 제 역할 중에 첫 번째와 두 번째인 base64 인코딩/디코딩 및 S3로 이미지 관리입니다.

1. 이미지 base64 인코딩/디코딩하기

안드로이드 클라이언트에서 이미지를 업로드 할 때, 서버로 base64 문자열로 이미지를 전송합니다. 이를 서버에서 받아 다시 디코딩 해서 S3로 올립니다.
반대로 서버에서 클라이언트로 이미지를 전송할 때는, 다시 S3에서 이미지를 받아와 base64로 인코딩해 안드로이드 클라이언트로 보냅니다.

이를 서비스 코드 내부에 구현했습니다.


S3ServiceImpl.java

...

    @Override
    public boolean decode(String base64Img, String fileName) {
        // 이미지 base64 문자열만 바로 받아와서 디코딩
        byte[] imageBytes = Base64.getDecoder().decode(base64Img);

        try (FileOutputStream fos = new FileOutputStream(fileName)) {
            fos.write(imageBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
...

디코딩 실패 시 false를 반환 하여 오류를 알립니다.


2. S3 사용을 위한 환경 설정하기

1) 의존성, 플러그인 설치하기

S3 사용을 위해서는 의존성, 그리고 intellij 기준 추가로 플러그인 설치가 필요합니다.

build.gradle

implementation 'org.springframework.cloud:spring-cloud-starter-aws:2.2.6.RELEASE'

위의 의존성을 추가해줍니다.(2023년 1월 기준 버전)


AWS Toolkit 플러그인을 설치해줍니다.

2) application.yml 수정 및 application-aws.yml 생성


application.yml

spring:
  profiles:
    include:
      - aws
cloud:
  aws:
    s3:
      bucket: 버킷 이름
      url: 버킷 url
    region:
      static: ap-northeast-2
    stack:
      auto: false
    credentials:
      instance-profile: true
  • spring.profiles.inlcude: - aws: application-aws.yml을 프로젝트에서 사용합니다.
  • cloud.aws.s3.region.staic: ap-northeast-2: 버킷의 리전을 나타냅니다 여기선 서울입니다.
  • cloud.aws.s3.stack.auto: false: EC2에서 CloudFormation을 통한 구성 시작을 비활성화합니다.(이 프로젝트에서 따로 설정하지 않았기 때문입니다.)
  • cloud.aws.s3.credentials.instance-profile: true: EC2 인스턴스의 IAM Role에 생성된 Key를 사용합니다.

S3와 연동을 위해 application.yml에 필요한 정보를 추가합니다.


application-aws.yml

cloud:
  aws:
    credentials:
      accessKey:
      secretKey: 
  • cloud.aws.credentilas: IAM 계정에서 발급받은 Key를 입력합니다. 보안에 유의해야합니다.

가장 중요한 작업으로 .gitignore에 application-aws.yml을 추가합니다.

3. AmazonS3 사용 환경 설정

S3Config.java 파일을 만들어 S3 API를 사용할 수 있도록 해줍니다.

1) Credential 생성

S3Config.java

@Configuration
public class S3Config {
    @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 AmazonS3 amazonS3Client() {
        AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
        return AmazonS3ClientBuilder
                .standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withRegion(region)
                .build();
    }
}
  • @Value(...): application-aws.yml 파일에서 Credential 생성을 위한 내용을 받아옵니다.
  • public AmazonS3 amazonS3Client(): AmazonS3 API 사용을 위한 Bean을 설정해줍니다.

2) 다운로드를 위한 TransferManager 생성

S3Config.java

@Configuration
public class S3Config {
...

    @Bean
    public TransferManager transferManager() {
        TransferManager transferManager = TransferManagerBuilder.standard()
                .withS3Client(amazonS3Client())
                .build();
        return transferManager;
    }
...
}
  • public TransferManager transferManager(): 버킷에서 이미지 파일 다운로드를 위한 transferManager Bean을 설정해줍니다.

4. 남은 할일

  • S3 API 사용으로 CRUD 생성
profile
여러가지를 시도하는 학생입니다

0개의 댓글