Notice
Recent Posts
Recent Comments
Link
반응형
관리 메뉴

쿵야지식떨이

[Infra] GCS 적용 (3) - GCS 프로젝트에 적용 본문

Infra

[Infra] GCS 적용 (3) - GCS 프로젝트에 적용

김쿵야 2024. 4. 22. 09:30
반응형

이번 글에서는 실제 프로젝트에 만든 GCS 프로젝트와 키를 사용하여 적용해 볼 것이다. 

저번 글에서 만들었던 프로젝트와 키는 테스트용으로 만든 것이라 프로젝트에 적용된 것과 이름이 약간 다를 수 있다..!


1. 프로젝트 설정 

1. build.gradle

// google cloud storage
   implementation group: 'com.google.cloud', name: 'spring-cloud-gcp-starter', version: '5.1.2'
   implementation group: 'com.google.cloud', name: 'spring-cloud-gcp-storage', version: '5.1.2'
  • 먼저 gcs 관련 코드를 작성하기 위해 gcs 의존성을 추가해줘야 한다. 
  • 현재 위 라이브러리의 가장 최신 버전인 5.1.2 버전으로 추가해 줬다. 
  • spring-cloud-gcp-starter는 Google Cloud Platform과의 통합을 쉽게 만들어주는 스타터 패키지를 제공한다.
  • spring-cloud-gcp-storage는 Google Cloud Storage와의 연동을 가능하게 해 준다. 

2. application.yml

spring:
  cloud:
    gcp:
      storage:
        credentials:
          location: classpath:gcs-key-file-name.json
        project-id: projectName
        bucket: bucketName

  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB
  • GCS key 파일을 yml이 있는 resources에 넣어놨다. 
  • location에 해당 파일의 경로를 작성하고 project-id와 bucket은 이전에 만든 저장소의 이름과 bucket 명을 작성하면 된다. 

2. 코드 구현 

1. GCSService

import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

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

@Service
public class GCSService {

    @Value("${spring.cloud.gcp.storage.bucket}")
    private String bucketName;

    public String uploadFile(MultipartFile file) throws IOException {
        // 인증 파일 이름 설정
        String keyFileName = "gcs-key-file-name.json";
        InputStream keyFile = ResourceUtils.getURL("classpath:" + keyFileName).openStream();

        // GCS 인증 및 서비스 초기화
        Storage storage = StorageOptions.newBuilder()
                .setCredentials(GoogleCredentials.fromStream(keyFile))
                .build()
                .getService();

        // 업로드할 파일의 Blob 정보 설정
        BlobInfo blobInfo = BlobInfo.newBuilder(bucketName, file.getOriginalFilename())
                .setContentType(file.getContentType()).build();

        // 파일 업로드
        Blob blob = storage.create(blobInfo, file.getInputStream());

        // 업로드된 파일의 GCS URL 반환
        return String.format("https://storage.googleapis.com/%s/%s", bucketName, blob.getName());
    }
}
  • GoogleCredentials.fromStream메서드를 사용하여 인증 파일로부터 인증 정보를 읽고, 이를 사용하여 Storage 인스턴스를 초기화
  • Storage 인스턴스를 통해 GCS와의 통신이 이루어진다.
  • Blob 정보를 설정하여 저장할 버킷 이름과 파일 이름, 파일의 콘텐츠 유형(ContentType)을 설정한다.
  • 설정한 Blob 정보와 파일 입력 스트림을 사용하여 GCS에 파일을 업로드한다.
    • 업로드된 파일은 Blob 객체로 반환된다. 

2. GCSController

import com.server.gummymurderer.exception.Response;
import com.server.gummymurderer.service.GCSService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/api/v1/gcs")
@RequiredArgsConstructor
public class GCSController {

    private final GCSService gcsService;

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public Response<String> objectUpload(@RequestPart("file") MultipartFile file) throws IOException {

        String url = gcsService.uploadFile(file);

        return Response.success(url);
    }

}
  • 요청 Content-Type은 multpart/form-data이며, 응답 Content-Type은 application/json으로 설정
  • 클라이언트로부터 전송받은 파일은 @RequestPart 어노테이션을 통해 MultpartFile 타입의 file 파라미터로 접근한다. 
  • 이때 전송받은 파일은 gcsService.uploadFile 메서드를 통해 Google Colud Storage에 업로드된다. 

3. Swagger Test

  • 파일 업로드 테스트를 위해 swagger로 파일 전송을 한다. 

  • 성공했다면 버킷에서 파일이 업로드된 것을 확인할 수 있다. 

 

반응형