diff --git a/CLAUDE.md b/CLAUDE.md index 949226a..257d148 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,7 +8,7 @@ - **JPA + QueryDSL** (MySQL) - **Spring Security** (JWT + Google OAuth2) - **Firebase Cloud Messaging** (푸시 알림) -- **AWS S3** (이미지 업로드) +- **Cloudflare R2** (이미지 업로드, AWS SDK v2 S3 호환 API) - **Apache POI** (Excel 생성) ## 빌드 & 실행 @@ -72,7 +72,7 @@ domain/{name}/ ## 서비스 의존성 ``` -ItemService → ItemRepository, S3Service +ItemService → ItemRepository, FileStorageService(R2Service) MemberService → MemberRepository, TokenProvider, PayerService NotificationService → NotificationRepository, NotificationPushOutboxService NotificationPushOutboxService → NotificationPushOutboxRepository @@ -223,7 +223,7 @@ global/ ├── exception/ # ApiException, ErrorCode, GlobalExceptionHandler ├── external/ │ ├── fcm/ # FCMConfig, FCMService -│ └── s3/ # S3Config, S3Service +│ └── r2/ # R2Config, R2Service (FileStorageService 구현체) ├── logging/ # LoggingFilter ├── security/ │ ├── jwt/ # TokenProvider, TokenAuthenticationFilter diff --git a/README.md b/README.md index 2a54f9b..5b985e0 100644 --- a/README.md +++ b/README.md @@ -162,7 +162,7 @@ Repository ── Spring Data JPA, QueryDSL 기반 데이터 접근 | Database | **MySQL**, HikariCP / 테스트용 H2 | | Security | Spring Security, Google OAuth2, JWT | | Messaging | Firebase Cloud Messaging, Spring Application Event, `@Async`, 스케줄러 | -| File Storage | **MinIO** (기존 AWS S3에서 이전) | +| File Storage | **Cloudflare R2** (AWS S3 → MinIO → R2 이전) | | Documentation | Springdoc OpenAPI / Swagger UI | | Build & Deploy | Gradle Kotlin DSL, Docker, Docker Hub, GitHub Actions, Coolify | | Logging | Kotlin Logging, Logback AsyncAppender | @@ -182,7 +182,7 @@ GitHub push (develop / main) ## 6. 실행 방법 -**요구 환경:** JDK 21, MySQL, MinIO, Google OAuth2 및 Firebase 자격증명. +**요구 환경:** JDK 21, MySQL, Cloudflare R2, Google OAuth2 및 Firebase 자격증명. ```bash # 프로젝트 클론 @@ -196,7 +196,7 @@ cd backend profile=dev ./gradlew bootRun ``` -주요 환경변수는 `DB_URL`, `DB_USERNAME`, `DB_PASSWORD`, `JWT_SECRET_KEY`, `JWT_ISSUER`, `OAUTH2_GOOGLE_CLIENT_ID`, `OAUTH2_GOOGLE_CLIENT_SECRET`, `MINIO_ENDPOINT`, `MINIO_ACCESS_KEY`, `MINIO_SECRET_KEY`, `MINIO_BUCKET`, `MINIO_BASE_URL`, `CORS_ALLOWED_ORIGINS`, `SWAGGER_SERVER_BASE_URL`, `LOGIN_REDIRECT_URL`입니다. Firebase 서비스 계정 설정도 필요합니다. 실제 값은 저장소에 커밋하지 않습니다. +주요 환경변수는 `DB_URL`, `DB_USERNAME`, `DB_PASSWORD`, `JWT_SECRET_KEY`, `JWT_ISSUER`, `OAUTH2_GOOGLE_CLIENT_ID`, `OAUTH2_GOOGLE_CLIENT_SECRET`, `R2_ENDPOINT`, `R2_ACCESS_KEY`, `R2_SECRET_KEY`, `R2_BUCKET`, `R2_PUBLIC_URL`, `CORS_ALLOWED_ORIGINS`, `SWAGGER_SERVER_BASE_URL`, `LOGIN_REDIRECT_URL`입니다. Firebase 서비스 계정 설정도 필요합니다. 실제 값은 저장소에 커밋하지 않습니다. - API 명세: 앱 실행 후 `/swagger` (Swagger UI), `/api-docs` (OpenAPI JSON) - 자세한 프로파일 설정: [`application-dev.yml`](https://github.com/billilge/backend/blob/develop/src/main/resources/application-dev.yml) diff --git a/build.gradle.kts b/build.gradle.kts index b60b484..4b8b3dd 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -47,7 +47,7 @@ dependencies { implementation("org.thymeleaf.extras:thymeleaf-extras-springsecurity6") - implementation("io.minio:minio:8.5.7") + implementation("software.amazon.awssdk:s3:2.54.15") implementation("javax.xml.bind:jaxb-api:2.3.1") implementation("org.apache.tika:tika-core:2.9.2") implementation("org.apache.tika:tika-parsers-standard-package:2.9.2") diff --git a/src/main/kotlin/site/billilge/api/backend/global/external/minio/MinioConfig.kt b/src/main/kotlin/site/billilge/api/backend/global/external/minio/MinioConfig.kt deleted file mode 100644 index c18ce8f..0000000 --- a/src/main/kotlin/site/billilge/api/backend/global/external/minio/MinioConfig.kt +++ /dev/null @@ -1,27 +0,0 @@ -package site.billilge.api.backend.global.external.minio - -import io.minio.MinioClient -import org.springframework.beans.factory.annotation.Value -import org.springframework.context.annotation.Bean -import org.springframework.context.annotation.Configuration - -@Configuration -class MinioConfig( - @Value("\${minio.endpoint}") - private val endpoint: String, - - @Value("\${minio.access-key}") - private val accessKey: String, - - @Value("\${minio.secret-key}") - private val secretKey: String, -) { - - @Bean - fun minioClient(): MinioClient { - return MinioClient.builder() - .endpoint(endpoint) - .credentials(accessKey, secretKey) - .build() - } -} diff --git a/src/main/kotlin/site/billilge/api/backend/global/external/minio/MinioService.kt b/src/main/kotlin/site/billilge/api/backend/global/external/minio/MinioService.kt deleted file mode 100644 index c8f2bd4..0000000 --- a/src/main/kotlin/site/billilge/api/backend/global/external/minio/MinioService.kt +++ /dev/null @@ -1,73 +0,0 @@ -package site.billilge.api.backend.global.external.minio - -import io.minio.MinioClient -import io.minio.PutObjectArgs -import io.minio.RemoveObjectArgs -import io.minio.StatObjectArgs -import io.minio.errors.ErrorResponseException -import org.springframework.beans.factory.annotation.Value -import org.springframework.stereotype.Service -import org.springframework.web.multipart.MultipartFile -import site.billilge.api.backend.global.exception.ApiException -import site.billilge.api.backend.global.exception.GlobalErrorCode -import site.billilge.api.backend.global.external.FileStorageService -import java.io.IOException -import java.util.* - -@Service -class MinioService( - private val minioClient: MinioClient, - @Value("\${minio.bucket}") - private val bucket: String, - @Value("\${minio.base-url}") - private val baseUrl: String, -) : FileStorageService { - - override fun uploadImageFile(imageFile: MultipartFile, newFileName: String): String? { - val originalName = imageFile.originalFilename ?: return null - - val ext = originalName.substring(originalName.lastIndexOf(".")) - val changedName = newFileName + ext - - try { - minioClient.putObject( - PutObjectArgs.builder() - .bucket(bucket) - .`object`(changedName) - .stream(imageFile.inputStream, imageFile.size, -1) - .contentType(imageFile.contentType) - .build() - ) - } catch (e: IOException) { - throw ApiException(GlobalErrorCode.IMAGE_UPLOAD_FAILED, e) - } - - return "${baseUrl}/${bucket}/${changedName}" - } - - override fun deleteImageFile(fileName: String) { - val imageKey = fileName.replace("${baseUrl}/${bucket}/", "") - - try { - minioClient.statObject( - StatObjectArgs.builder() - .bucket(bucket) - .`object`(imageKey) - .build() - ) - } catch (e: ErrorResponseException) { - throw ApiException(GlobalErrorCode.IMAGE_NOT_FOUND) - } - - try { - minioClient.removeObject( - RemoveObjectArgs.builder() - .bucket(bucket) - .`object`(imageKey) - .build() - ) - } catch (e: IOException) { - throw ApiException(GlobalErrorCode.IMAGE_DELETE_FAILED, e) - } - } -} diff --git a/src/main/kotlin/site/billilge/api/backend/global/external/r2/R2Config.kt b/src/main/kotlin/site/billilge/api/backend/global/external/r2/R2Config.kt new file mode 100644 index 0000000..af00d9b --- /dev/null +++ b/src/main/kotlin/site/billilge/api/backend/global/external/r2/R2Config.kt @@ -0,0 +1,40 @@ +package site.billilge.api.backend.global.external.r2 + +import org.springframework.beans.factory.annotation.Value +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider +import software.amazon.awssdk.core.checksums.RequestChecksumCalculation +import software.amazon.awssdk.core.checksums.ResponseChecksumValidation +import software.amazon.awssdk.regions.Region +import software.amazon.awssdk.services.s3.S3Client +import java.net.URI + +@Configuration +class R2Config( + @Value("\${r2.endpoint}") + private val endpoint: String, + + @Value("\${r2.access-key}") + private val accessKey: String, + + @Value("\${r2.secret-key}") + private val secretKey: String, +) { + + @Bean + fun r2Client(): S3Client { + return S3Client.builder() + .endpointOverride(URI.create(endpoint)) + .region(Region.of("auto")) + .credentialsProvider( + StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey)) + ) + .forcePathStyle(true) + // R2는 AWS SDK 기본값(모든 요청에 CRC 체크섬 부착)을 완전히 지원하지 않으므로 필요한 경우에만 계산 + .requestChecksumCalculation(RequestChecksumCalculation.WHEN_REQUIRED) + .responseChecksumValidation(ResponseChecksumValidation.WHEN_REQUIRED) + .build() + } +} diff --git a/src/main/kotlin/site/billilge/api/backend/global/external/r2/R2Service.kt b/src/main/kotlin/site/billilge/api/backend/global/external/r2/R2Service.kt new file mode 100644 index 0000000..1619506 --- /dev/null +++ b/src/main/kotlin/site/billilge/api/backend/global/external/r2/R2Service.kt @@ -0,0 +1,83 @@ +package site.billilge.api.backend.global.external.r2 + +import org.springframework.beans.factory.annotation.Value +import org.springframework.stereotype.Service +import org.springframework.web.multipart.MultipartFile +import site.billilge.api.backend.global.exception.ApiException +import site.billilge.api.backend.global.exception.GlobalErrorCode +import site.billilge.api.backend.global.external.FileStorageService +import software.amazon.awssdk.core.exception.SdkException +import software.amazon.awssdk.core.sync.RequestBody +import software.amazon.awssdk.services.s3.S3Client +import software.amazon.awssdk.services.s3.model.DeleteObjectRequest +import software.amazon.awssdk.services.s3.model.HeadObjectRequest +import software.amazon.awssdk.services.s3.model.PutObjectRequest +import software.amazon.awssdk.services.s3.model.S3Exception +import java.io.IOException + +@Service +class R2Service( + private val r2Client: S3Client, + @Value("\${r2.bucket}") + private val bucket: String, + @Value("\${r2.public-url}") + publicUrl: String, +) : FileStorageService { + + // R2 공개 URL(r2.dev 또는 커스텀 도메인)은 버킷에 직접 연결되므로 경로에 버킷명이 들어가지 않는다 + private val publicUrl = publicUrl.trimEnd('/') + + override fun uploadImageFile(imageFile: MultipartFile, newFileName: String): String? { + val originalName = imageFile.originalFilename ?: return null + + val ext = originalName.substring(originalName.lastIndexOf(".")) + val key = newFileName + ext + + val request = PutObjectRequest.builder() + .bucket(bucket) + .key(key) + .contentType(imageFile.contentType) + .build() + + try { + imageFile.inputStream.use { + r2Client.putObject(request, RequestBody.fromInputStream(it, imageFile.size)) + } + } catch (e: IOException) { + throw ApiException(GlobalErrorCode.IMAGE_UPLOAD_FAILED, e) + } catch (e: SdkException) { + throw ApiException(GlobalErrorCode.IMAGE_UPLOAD_FAILED, e) + } + + return "$publicUrl/$key" + } + + override fun deleteImageFile(fileName: String) { + val key = fileName.removePrefix("$publicUrl/") + + try { + r2Client.headObject( + HeadObjectRequest.builder() + .bucket(bucket) + .key(key) + .build() + ) + } catch (e: S3Exception) { + if (e.statusCode() == 404) throw ApiException(GlobalErrorCode.IMAGE_NOT_FOUND) + throw ApiException(GlobalErrorCode.IMAGE_DELETE_FAILED, e) + } catch (e: SdkException) { + throw ApiException(GlobalErrorCode.IMAGE_DELETE_FAILED, e) + } + + try { + r2Client.deleteObject( + DeleteObjectRequest.builder() + .bucket(bucket) + .key(key) + .build() + ) + } catch (e: SdkException) { + throw ApiException(GlobalErrorCode.IMAGE_DELETE_FAILED, e) + } + } +} diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml index eb2e6b1..ee52c14 100644 --- a/src/main/resources/application-dev.yml +++ b/src/main/resources/application-dev.yml @@ -77,12 +77,12 @@ login: cors: allowed-origins: ${CORS_ALLOWED_ORIGINS} -minio: - endpoint: ${MINIO_ENDPOINT} - access-key: ${MINIO_ACCESS_KEY} - secret-key: ${MINIO_SECRET_KEY} - bucket: ${MINIO_BUCKET} - base-url: ${MINIO_BASE_URL} +r2: + endpoint: ${R2_ENDPOINT} + access-key: ${R2_ACCESS_KEY} + secret-key: ${R2_SECRET_KEY} + bucket: ${R2_BUCKET} + public-url: ${R2_PUBLIC_URL} swagger: server: diff --git a/src/main/resources/application-prod.yml b/src/main/resources/application-prod.yml index 8774db8..ac013fe 100644 --- a/src/main/resources/application-prod.yml +++ b/src/main/resources/application-prod.yml @@ -68,12 +68,12 @@ login: cors: allowed-origins: ${CORS_ALLOWED_ORIGINS} -minio: - endpoint: ${MINIO_ENDPOINT} - access-key: ${MINIO_ACCESS_KEY} - secret-key: ${MINIO_SECRET_KEY} - bucket: ${MINIO_BUCKET} - base-url: ${MINIO_BASE_URL} +r2: + endpoint: ${R2_ENDPOINT} + access-key: ${R2_ACCESS_KEY} + secret-key: ${R2_SECRET_KEY} + bucket: ${R2_BUCKET} + public-url: ${R2_PUBLIC_URL} swagger: server: