Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 생성)

## 빌드 & 실행
Expand Down Expand Up @@ -72,7 +72,7 @@ domain/{name}/
## 서비스 의존성

```
ItemService → ItemRepository, S3Service
ItemService → ItemRepository, FileStorageService(R2Service)
MemberService → MemberRepository, TokenProvider, PayerService
NotificationService → NotificationRepository, NotificationPushOutboxService
NotificationPushOutboxService → NotificationPushOutboxRepository
Expand Down Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand All @@ -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
# 프로젝트 클론
Expand All @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -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()
}
}
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
12 changes: 6 additions & 6 deletions src/main/resources/application-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
12 changes: 6 additions & 6 deletions src/main/resources/application-prod.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading