Notice
Recent Posts
Recent Comments
Link
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
Tags
more
Archives
Today
Total
관리 메뉴

개발계발

[MSA 프로젝트] AWS S3 연결하기 본문

프로젝트

[MSA 프로젝트] AWS S3 연결하기

Ju_Nik_E 2024. 7. 19. 16:25
어려운 건 아니지만 프로젝트를 진행하면서 AWS S3 연결할 때마다 방법을 까먹어서 기록해놓기

 

1. 의존성 추가

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

 

2. yml파일 aws관련 코드 작성

cloud:
  aws:
    stack:
      auto: false
    region:
      static: AWS지역
    credentials:
      access-key: 액세스키
      secret-key: 비밀키
    s3:
      bucket: 버킷명​

 

3. S3Config 파일 작성

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
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;

@Configuration
public class S3Config {

    @Value("${cloud.aws.credentials.access-key}")
    private String accessKey;

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

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

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

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

 

4. S3Serivce 파일 작성(기본적으로 파일 업로드, 삭제기능, 필요 시 추가)

import com.amazonaws.services.s3.AmazonS3;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
@RequiredArgsConstructor
public class S3Service {
    private final AmazonS3 amazonS3Client;

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

    public String uploadFile(String fileName, MultipartFile file) throws IOException {
        amazonS3Client.putObject(bucket, fileName, file.getInputStream(), null);
        return amazonS3Client.getUrl(bucket, fileName).toString();
    }

    public void deleteFile(String fileName) {
        amazonS3Client.deleteObject(bucket, fileName);
    }
}

 

5. 아래와 같이 서비스 코드에 S3Service 주입하고 사용하면 끝!

@Slf4j
@Service
@RequiredArgsConstructor
public class LectureNoteService {
    private final LectureNoteRepository lectureNoteRepository;
    private final S3Service s3Service;
    
    /**
     * 강의 노트 등록
     */
    @Transactional
    public LectureNoteResponseDto create(Long lectureId, String title, MultipartFile file) {
        String fileUrl;
        try {
            String fileName = "lecture-notes/" + UUID.randomUUID() + "-" + file.getOriginalFilename();
            fileUrl = s3Service.uploadFile(fileName, file);
        } catch (IOException e) {
            throw new CustomException(ErrorCode.FILE_UPLOAD_FAILED);
        }

        LectureNote lectureNote = LectureNote.builder()
                .lectureId(lectureId)
                .title(title)
                .fileUrl(fileUrl)
                .build();

        LectureNote savedLectureNote = lectureNoteRepository.save(lectureNote);

        return LectureNoteResponseDto.builder()
                .noteId(savedLectureNote.getNoteId())
                .lectureId(savedLectureNote.getLectureId())
                .title(savedLectureNote.getTitle())
                .fileUrl(savedLectureNote.getFileUrl())
                .build();
    }
}​

 

'프로젝트' 카테고리의 다른 글

[MSA 프로젝트] 각 서비스끼리 통신하기 만들기  (0) 2024.07.19