diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..8af972cde --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..1f38475c8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,46 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +# QueryDSL generated files +build/ +generated/ +**/build/ +**/generated/ + +# Ignore specific Q classes (if needed) +**/Q*.java + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/README.md b/README.md index 5fcc66b4d..68f7d9035 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,83 @@ -## [본 과정] 이커머스 핵심 프로세스 구현 -[단기 스킬업 Redis 교육 과정](https://hh-skillup.oopy.io/) 을 통해 상품 조회 및 주문 과정을 구현하며 현업에서 발생하는 문제를 Redis의 핵심 기술을 통해 해결합니다. -> Indexing, Caching을 통한 성능 개선 / 단계별 락 구현을 통한 동시성 이슈 해결 (낙관적/비관적 락, 분산락 등) +## Multi Module Design +Module을 나누는 기준은 여러 개가 있지만, 이번 프로젝트에서는 Layered Architecture 에서 설명되는 Layer 별로 구분하였습니다. +- api: 사용자의 요청을 받고, 응답한다. + - 본래, presentation과 application 두 개의 모듈로 분리되어있던 구조를 수정하였습니다. + - 사용자의 요청을 받고 처리한다는 점에서, Error와 Response를 한 곳에서 관리하기 위함입니다. +- domain: 시스템이 제공할 도메인 규칙을 구현한다. +- infra: 외부 시스템과의 연동을 담당한다. +- 본래 존재하였던 core 모듈을 삭제하였습니다. + - 실제로 공통 역할이 아니지만 core(or common) 모듈에 패키지를 생성해서 정의하는 경우를 방지하기 위함입니다. + - 현재까지의 요구사항에서는 core 모듈에 들어갈 기능이 없다고 판단되었습니다. + +각 module은 하위 module에만 의존합니다.
+JPA 를 다른 ORM 으로 변경될 가능성은 낮다고 판단하여 PA 는 생산성을 위해서 Entity 와 Repository 를 Domain 으로 끌어 올려 사용하였습니다. +JPA 를 제외한 나머지는 저수준의 변경사항으로 부터 고수준을 지키는 방식을 사용합니다. + +## Table Design +![img_2.png](img_2.png) +- Movie 테이블과 Theater 테이블은 N:N 관계로 중간에 Screening 테이블을 두고 있습니다. + - Theater 별로 시간표가 구분되는 것을 고려하여 Screening 테이블은 상영 시간표 정보를 포함하고 있습니다. +- 좌석별 등급 등 좌석 개별의 특성이 추가될 수 있다고 생각하여 Seat 테이블을 생성하였습니다. +- Theater 테이블과 Seat 테이블은 1:N 관계입니다. +- Seat 테이블과 Reservation 테이블은 1:1 관계입니다. + - 공유 자원인 Seat과 행위인 Reservation을 분리하기 위함입니다. +- Reservation 테이블과 User 테이블은 1:1 관계입니다. + +## N+1 문제 해결 +저는 N+1 문제가 ID 참조을 사용하기 때문이라고 생각합니다. 따라서 해당 프로젝트에 간접참조를 사용하여, N+1 문제를 해결하고자 합니다. +뿐만 아니라, 간접 참조를 사용하면 도메인 간 물리적인 연결을 제거하기 때문에 도메인 간 의존을 강제적으로 제거되고, FK의 데이터 정합성을 따지기 위한 성능 오버헤드를 줄이며, 데이터 수정 시의 작업 순서가 강제됨에 따라 발생하는 더 큰 수정 개발을 방지할 수 있습니다. + +대신, 애플리케이션 단에서 무결성 관리를 관리하도록 합니다. (삽입/수정/삭제) + +## 성능 테스트 보고서 +- DAU: 500명 +- duration : '5m' 으로 진행 +- 95% 요청이 200ms 이하, 실패율 1% 이하를 thresholds로 추가 +### 1. INDEX 적용 전 +- 영화 300개, 상영관 4개, 시간표 1,000개 +- 실행 계획 +```sql +EXPLAIN ANALYZE SELECT m.id, m.name, m.grade, m.release_date, m.thumbnail, m.running_time, m.genre, t.id, t.name, s.start_at, s.end_at FROM movie m JOIN screening s ON m.id = s.movie_id JOIN theater t ON s.theater_id = t.id WHERE s.start_at >= NOW(); +``` +![img_3.png](img_3.png) + +-> 풀테이블 스캔 전략 +- 부하테스트
+![img_4.png](img_4.png) + +-> 95% 응답 시간이 1.1s 이므로 실패 + +### 2. INDEX 적용 후 +- Screening 테이블에 start_at에 대한 인덱스 생성 +- 영화 300개, 상영관 4개, 시간표 1,000개 +- 실행 계획
+![img_5.png](img_5.png) + +-> 인덱스 레인지 전략 +- 부하테스트
+![img_6.png](img_6.png) + +-> 95% 응답 시간이 12.67ms로, 성능이 약 86배 향상 + +### 3. Local Caching 적용 후 +* 현재 상영 중인 영화 조회 쿼리는, LocalDateTime을 기준으로 필터링하기 때문에, 캐싱에 의미가 없습니다. 따라서, start_at 기준을 뺀, 상영중인 영화가 아닌 모든 영화를 조회하는 API를 가지고 캐싱을 진행하였습니다. +=> nowShowing에 대한 쿼리 파라미터를 추가하여 TRUE이면 상영중인 영화, FALSE 이면 모든 영화가 조회되도록 코드를 수정하였습니다. +- 데이터를 영화 500개, 상영관 3개, 시간표 3,000개로 늘렸습니다. +- 실행 계획 +```sql +EXPLAIN ANALYZE SELECT m.id, m.name, m.grade, m.release_date, m.thumbnail, m.running_time, m.genre, t.id, t.name, s.start_at, s.end_at FROM movie m JOIN screening s ON m.id = s.movie_id JOIN theater t ON s.theater_id = t.id WHERE m.genre = 'HORROR' AND m.name LIKE '%3%'; +``` + +- 성능 개선 전 부하 테스트(쿼리가 수정되고 데이터가 늘어나서 다시 수행)
+![img_7.png](img_7.png) + +-> 95%의 응답 시간이 747.93ms 이므로 실패 +- 로컬 캐싱 적용 후 부하 테스트
+![img_8.png](img_8.png) + +-> 95%의 응답 시간이 6.38ms 로, 성능이 약 117배 향상되었습니다. + +### 4. Global Caching 적용 후 +![img_9.png](img_9.png) + +-> 95%의 응답 시간이 7.33ms로, 로컬 캐싱보다는 느리지만 캐싱 적용 전보다 훨씬 성능이 향상되었습니다. \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 000000000..f2bdc8e33 --- /dev/null +++ b/build.gradle @@ -0,0 +1,52 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.4.1' + id 'io.spring.dependency-management' version '1.1.7' +} + +repositories { + mavenCentral() +} + +subprojects { + // 모든 하위 모듈들에 이 설정을 적용 + group 'com.example' + version '0.0.1-SNAPSHOT' + sourceCompatibility = '17' + targetCompatibility = '17' + + apply plugin: 'java' + apply plugin: 'java-library' + apply plugin: 'org.springframework.boot' + apply plugin: 'io.spring.dependency-management' + + configurations { + compileOnly { + extendsFrom annotationProcessor + } + } + + repositories { + mavenCentral() + } + + dependencies { // 모든 하위 모듈에 추가 될 의존성 목록입니다. + implementation 'org.springframework.boot:spring-boot-starter' + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'com.h2database:h2' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + testImplementation 'org.junit.jupiter:junit-jupiter:5.7.1' + testImplementation "org.testcontainers:testcontainers:1.19.0" + testImplementation "org.testcontainers:junit-jupiter:1.19.0" + + implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2' + implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.15.2' + + } + + test { + useJUnitPlatform() + } +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 000000000..9061d5e8e --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,16 @@ +version: '3.8' +services: + mysql: + image: mysql:latest # 이미 로컬에 있는 MySQL 이미지 사용 + environment: + MYSQL_ROOT_PASSWORD: 1234 # 루트 계정 비밀번호 + MYSQL_DATABASE: hanghae99 # 생성할 기본 데이터베이스 + MYSQL_USER: user # 사용자 계정 (선택) + MYSQL_PASSWORD: password # 사용자 비밀번호 (선택) + ports: + - "3305:3306" # 호스트의 3306 포트를 컨테이너의 3306 포트와 연결 + + redis: + image: redis:latest # 이미 로컬에 있는 Redis 이미지 사용 + ports: + - "6378:6379" # 호스트의 6378 포트를 컨테이너의 6379 포트와 연결 diff --git a/domain/build.gradle b/domain/build.gradle new file mode 100644 index 000000000..304b22fe1 --- /dev/null +++ b/domain/build.gradle @@ -0,0 +1,9 @@ +bootJar.enabled = false + +jar.enabled = true + +dependencies { + implementation project(':infra') + + api ('org.springframework.boot:spring-boot-starter-validation') +} \ No newline at end of file diff --git a/domain/src/main/java/com/example/message/MessageService.java b/domain/src/main/java/com/example/message/MessageService.java new file mode 100644 index 000000000..487588837 --- /dev/null +++ b/domain/src/main/java/com/example/message/MessageService.java @@ -0,0 +1,15 @@ +package com.example.message; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +@Slf4j +@Service +public class MessageService { + + public void send() throws InterruptedException { + Thread.sleep(500); + log.info("예매가 성공적으로 되었습니다."); + } + +} diff --git a/domain/src/main/java/com/example/movie/converter/DtoConverter.java b/domain/src/main/java/com/example/movie/converter/DtoConverter.java new file mode 100644 index 000000000..97620e8b0 --- /dev/null +++ b/domain/src/main/java/com/example/movie/converter/DtoConverter.java @@ -0,0 +1,57 @@ +package com.example.movie.converter; + +import com.example.jpa.repository.movie.dto.MoviesDetailDto; +import com.example.movie.dto.MoviesDetailResponse; +import com.example.movie.dto.ScreeningTimeDetail; +import com.example.movie.dto.ScreeningsDetail; +import lombok.NoArgsConstructor; +import org.springframework.stereotype.Component; + +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + +@Component +@NoArgsConstructor +public class DtoConverter { + public List moviesNowScreening(List dbResults) { + return dbResults.stream() + .collect(Collectors.groupingBy(MoviesDetailDto::getMovieId)) + .entrySet().stream() + .map(entry -> { + Long movieId = entry.getKey(); + List groupedByMovie = entry.getValue(); + + + MoviesDetailDto firstEntry = groupedByMovie.get(0); + + + List screeningsDetails = groupedByMovie.stream() + .collect(Collectors.groupingBy(MoviesDetailDto::getTheaterId)) + .entrySet().stream() + .map(theaterEntry -> { + Long theaterId = theaterEntry.getKey(); + String theaterName = theaterEntry.getValue().get(0).getTheaterName(); + List screeningTimes = theaterEntry.getValue().stream() + .sorted(Comparator.comparing(MoviesDetailDto::getStartAt)) + .map(dto -> new ScreeningTimeDetail(dto.getStartAt(), dto.getEndAt())) + .toList(); + return new ScreeningsDetail(theaterId, theaterName, screeningTimes); + }) + .toList(); + + // Create the final DTO + return new MoviesDetailResponse( + movieId, // Add movieId here + firstEntry.getMovieName(), + firstEntry.getGrade(), + firstEntry.getReleaseDate(), + firstEntry.getThumbnail(), + firstEntry.getRunningTime(), + firstEntry.getGenre(), + screeningsDetails + ); + }) + .toList(); + } +} diff --git a/domain/src/main/java/com/example/movie/dto/MoviesDetailResponse.java b/domain/src/main/java/com/example/movie/dto/MoviesDetailResponse.java new file mode 100644 index 000000000..5fb597503 --- /dev/null +++ b/domain/src/main/java/com/example/movie/dto/MoviesDetailResponse.java @@ -0,0 +1,19 @@ +package com.example.movie.dto; + +import com.example.jpa.entity.movie.Genre; +import com.example.jpa.entity.movie.Grade; + +import java.time.LocalDate; +import java.util.List; + +public record MoviesDetailResponse( + Long movieId, + String movieName, + Grade grade, + LocalDate releaseDate, + String thumbnail, + Long runningTime, + Genre genre, + List screeningsDetails +) { +} diff --git a/domain/src/main/java/com/example/movie/dto/ScreeningTimeDetail.java b/domain/src/main/java/com/example/movie/dto/ScreeningTimeDetail.java new file mode 100644 index 000000000..235d3b064 --- /dev/null +++ b/domain/src/main/java/com/example/movie/dto/ScreeningTimeDetail.java @@ -0,0 +1,9 @@ +package com.example.movie.dto; + +import java.time.LocalDateTime; + +public record ScreeningTimeDetail( + LocalDateTime startAt, + LocalDateTime endAt +) { +} diff --git a/domain/src/main/java/com/example/movie/dto/ScreeningsDetail.java b/domain/src/main/java/com/example/movie/dto/ScreeningsDetail.java new file mode 100644 index 000000000..7ce311976 --- /dev/null +++ b/domain/src/main/java/com/example/movie/dto/ScreeningsDetail.java @@ -0,0 +1,10 @@ +package com.example.movie.dto; + +import java.util.List; + +public record ScreeningsDetail( + Long theaterId, + String theater, + List screeningTimes +) { +} diff --git a/domain/src/main/java/com/example/movie/service/MovieCacheService.java b/domain/src/main/java/com/example/movie/service/MovieCacheService.java new file mode 100644 index 000000000..cd9d73042 --- /dev/null +++ b/domain/src/main/java/com/example/movie/service/MovieCacheService.java @@ -0,0 +1,27 @@ +package com.example.movie.service; + +import com.example.jpa.entity.movie.Genre; +import com.example.jpa.repository.movie.MovieRepository; +import com.example.jpa.repository.movie.dto.MoviesDetailDto; +import lombok.RequiredArgsConstructor; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +@RequiredArgsConstructor +public class MovieCacheService { + + private final MovieRepository movieRepository; + + @Cacheable( + cacheNames = "getMoviesByGenre", + key = "'movies:genre:' + #p0", + cacheManager = "cacheManager" + ) + public List getMoviesByGenre(String genre) { + return movieRepository.searchWithFiltering(null, Genre.valueOf(genre), null); + } + +} diff --git a/domain/src/main/java/com/example/movie/service/MovieService.java b/domain/src/main/java/com/example/movie/service/MovieService.java new file mode 100644 index 000000000..62ded5880 --- /dev/null +++ b/domain/src/main/java/com/example/movie/service/MovieService.java @@ -0,0 +1,61 @@ +package com.example.movie.service; + +import com.example.movie.converter.DtoConverter; +import com.example.movie.dto.MoviesDetailResponse; +import com.example.jpa.entity.movie.Genre; +import com.example.jpa.repository.movie.dto.MoviesDetailDto; +import com.example.movie.dto.ScreeningTimeDetail; +import com.example.movie.dto.ScreeningsDetail; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.util.Comparator; +import java.util.List; + +@Service +@RequiredArgsConstructor +public class MovieService { + + private final MovieCacheService movieCacheService; + private final DtoConverter dtoConverter; + + public List getMovies(LocalDateTime now, Boolean isNowShowing, Genre genre, String search) { + List cachedMovies = movieCacheService.getMoviesByGenre(genre.toString()); + List moviesDetailResponses = dtoConverter.moviesNowScreening(cachedMovies); + return filterByStartAtAndTitle(now, isNowShowing, search, moviesDetailResponses); + } + + private static List filterByStartAtAndTitle(LocalDateTime now, Boolean isNowShowing, String search, List cachedMovies) { + return cachedMovies.stream() + .map(movie -> { + List filteredScreenings = movie.screeningsDetails().stream() + .map(screening -> { + List filteredTimes = screening.screeningTimes().stream() + .filter(time -> isNowShowing == null || !isNowShowing || time.startAt().isAfter(now)) + .toList(); + return new ScreeningsDetail(screening.theaterId(), screening.theater(), filteredTimes); + }) + .filter(screening -> !screening.screeningTimes().isEmpty()) + .toList(); + + return new MoviesDetailResponse( + movie.movieId(), + movie.movieName(), + movie.grade(), + movie.releaseDate(), + movie.thumbnail(), + movie.runningTime(), + movie.genre(), + filteredScreenings + ); + }) + .filter(movie -> { + boolean matchesSearch = search == null || movie.movieName().toLowerCase().contains(search.toLowerCase()); + return !movie.screeningsDetails().isEmpty() && matchesSearch; + }) + .sorted(Comparator.comparing(MoviesDetailResponse::releaseDate).reversed()) + .toList(); + } + +} diff --git a/domain/src/main/java/com/example/reservation/dto/ReservationRequest.java b/domain/src/main/java/com/example/reservation/dto/ReservationRequest.java new file mode 100644 index 000000000..a6c386573 --- /dev/null +++ b/domain/src/main/java/com/example/reservation/dto/ReservationRequest.java @@ -0,0 +1,9 @@ +package com.example.reservation.dto; + +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; + +import java.util.List; + +public record ReservationRequest(@NotNull Long userId, @NotNull Long screeningId, @NotNull @NotEmpty List<@NotEmpty String> seats){ +} diff --git a/domain/src/main/java/com/example/reservation/service/ReservationService.java b/domain/src/main/java/com/example/reservation/service/ReservationService.java new file mode 100644 index 000000000..da624b5c0 --- /dev/null +++ b/domain/src/main/java/com/example/reservation/service/ReservationService.java @@ -0,0 +1,108 @@ +package com.example.reservation.service; + +import com.example.jpa.entity.movie.Screening; +import com.example.jpa.entity.reservation.Reservation; +import com.example.jpa.entity.theater.Seat; +import com.example.jpa.entity.user.entity.User; +import com.example.jpa.repository.movie.ScreeningRepository; +import com.example.jpa.repository.movie.SeatRepository; +import com.example.jpa.repository.reservation.ReservationRepository; +import com.example.jpa.repository.user.UserRepository; +import com.example.message.MessageService; +import com.example.redis.DistributedLockService; +import com.example.reservation.dto.ReservationRequest; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@RequiredArgsConstructor +public class ReservationService { + + private static final String USER_NOT_FOUND = "존재하지 않는 유저입니다."; + + private static final String SCREENING_NOT_FOUND = "존재하지 않는 상영 시간표입니다."; + + private static final String SEAT_NOT_FOUND = "존재하지 않는 좌석입니다."; + + private static final String RESERVATION_MUST_BE_UNDER_MAX = "예매 가능한 좌석 수를 초과하였습니다."; + + private static final String SEATS_MUST_BE_ADJACENT = "인접한 좌석으로만 예매 가능합니다."; + + private static final String SEAT_ALREADY_BE_MADE_RESERVATION = "이미 예매된 좌석입니다."; + + private static final Integer MAX_RESERVATION_PER_PERSON = 5; + + private final ScreeningRepository screeningRepository; + + private final ReservationRepository reservationRepository; + + private final SeatRepository seatRepository; + + private final UserRepository userRepository; + + private final MessageService messageService; + + private final DistributedLockService distributedLockService; + + @Transactional + public void reserveSeat(ReservationRequest reservationRequest) throws InterruptedException { + User findUser = userRepository.findById(reservationRequest.userId()).orElseThrow(() -> + new IllegalArgumentException(USER_NOT_FOUND)); + + Screening screening = screeningRepository.findById(reservationRequest.screeningId()).orElseThrow(() -> + new IllegalArgumentException(SCREENING_NOT_FOUND)); + + if (reservationRequest.seats().size() > MAX_RESERVATION_PER_PERSON) { + throw new IllegalArgumentException(RESERVATION_MUST_BE_UNDER_MAX); + } + + if (!areSeatsAdjacent(reservationRequest.seats())) { + throw new IllegalArgumentException(SEATS_MUST_BE_ADJACENT); + } + + if (reservationRepository.getReservationCount(findUser.getId(),screening.getId()) + reservationRequest.seats().size() > MAX_RESERVATION_PER_PERSON ) { + throw new IllegalStateException(RESERVATION_MUST_BE_UNDER_MAX); + } + + distributedLockService.executeWithLockAndReturn(() -> { + for (String position : reservationRequest.seats()) { + Seat findSeat = seatRepository.findByPositionAndScreeningId(position, screening.getId()).orElseThrow(() -> + new IllegalArgumentException(SEAT_NOT_FOUND)); + + if (reservationRepository.existsBySeatIdAndScreeningId(findSeat.getId(), screening.getId())) { + throw new IllegalArgumentException(SEAT_ALREADY_BE_MADE_RESERVATION); + } + + Reservation reservation = new Reservation(); + reservation.reserve(findUser.getId(), findSeat.getId(), screening.getId()); + reservationRepository.save(reservation); + } + return null; + }, reservationRequest.screeningId(), reservationRequest.seats(), 1L, 5L); + messageService.send(); + } + + private boolean areSeatsAdjacent(List seats) { + for (int i = 0; i < seats.size() - 1; i++) { + String current = seats.get(i); + String next = seats.get(i + 1); + if (!areSeatsNextToEachOther(current, next)) { + return false; + } + } + return true; + } + + private boolean areSeatsNextToEachOther(String current, String next) { + char currentRow = current.charAt(0); + char nextRow = next.charAt(0); + int currentSeat = Integer.parseInt(current.substring(1)); + int nextSeat = Integer.parseInt(next.substring(1)); + + return currentRow == nextRow && nextSeat == currentSeat + 1; + } + +} diff --git a/domain/src/test/java/com/example/TestConfiguration.java b/domain/src/test/java/com/example/TestConfiguration.java new file mode 100644 index 000000000..4fb93008e --- /dev/null +++ b/domain/src/test/java/com/example/TestConfiguration.java @@ -0,0 +1,14 @@ +package com.example; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class TestConfiguration { + + @Test + void contextLoads(){ + + } + +} \ No newline at end of file diff --git a/domain/src/test/java/com/example/movie/converter/DtoConverterTest.java b/domain/src/test/java/com/example/movie/converter/DtoConverterTest.java new file mode 100644 index 000000000..af3744243 --- /dev/null +++ b/domain/src/test/java/com/example/movie/converter/DtoConverterTest.java @@ -0,0 +1,73 @@ +package com.example.movie.converter; + +import com.example.jpa.entity.movie.Genre; +import com.example.jpa.entity.movie.Grade; +import com.example.jpa.repository.movie.dto.MoviesDetailDto; +import com.example.movie.dto.MoviesDetailResponse; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +class DtoConverterTest { + @Test + @DisplayName("현재 상영중인 영화를 영화ID와 상영관을 기준으로 성공적으로 그룹핑한다.") + void 현재상영중인_영화조회_그룹핑_성공(){ + //given + LocalDateTime now = LocalDateTime.now(); + List dbResults = initData(now); + + //when + DtoConverter dtoConvertor = new DtoConverter(); + List result = dtoConvertor.moviesNowScreening(dbResults); + + //then + assertThat(result).hasSize(2); // 영화 ID로 그룹화 결과 두 개 (Movie A, Movie B) + + MoviesDetailResponse movieA = result.get(0); + assertThat(movieA.movieId()).isEqualTo(1L); // Movie A + assertThat(movieA.screeningsDetails()).hasSize(2); // Theater 1, Theater 2 + assertThat(movieA.screeningsDetails().get(0).screeningTimes()) + .extracting("startAt") + .isSorted(); // Theater 1 시간표 정렬 검증 + assertThat(movieA.screeningsDetails().get(1).screeningTimes()) + .extracting("startAt") + .isSorted(); // Theater 2 시간표 정렬 검증 + + MoviesDetailResponse movieB = result.get(1); + assertThat(movieB.movieId()).isEqualTo(2L); // Movie B + assertThat(movieB.screeningsDetails()).hasSize(1); // Theater 1만 포함 + assertThat(movieB.screeningsDetails().get(0).screeningTimes()) + .extracting("startAt") + .isSorted(); + } + + private static List initData(LocalDateTime now) { + return List.of( + new MoviesDetailDto( + 1L, "Movie A", Grade.ALL_AGE, LocalDate.of(2023, 12, 15), + "thumbnailA.jpg", 120L, Genre.ACTION, 1L, "Theater 1", + now.plusHours(1), now.plusHours(3) + ), + new MoviesDetailDto( + 1L, "Movie A", Grade.ALL_AGE, LocalDate.of(2023, 12, 15), + "thumbnailA.jpg", 120L, Genre.ACTION, 1L, "Theater 1", + now.plusHours(3), now.plusHours(5) + ), + new MoviesDetailDto( + 1L, "Movie A", Grade.ALL_AGE, LocalDate.of(2023, 12, 15), + "thumbnailA.jpg", 120L, Genre.ACTION, 2L, "Theater 2", + now.plusHours(2), now.plusHours(4) + ), + new MoviesDetailDto( + 2L, "Movie B", Grade.FROM_12_AGE, LocalDate.of(2024, 1, 10), + "thumbnailB.jpg", 130L, Genre.ROMANCE, 1L, "Theater 1", + now.plusHours(3), now.plusHours(5) + ) + ); + } +} \ No newline at end of file diff --git a/domain/src/test/java/com/example/movie/service/MovieServiceTest.java b/domain/src/test/java/com/example/movie/service/MovieServiceTest.java new file mode 100644 index 000000000..40e7f0a64 --- /dev/null +++ b/domain/src/test/java/com/example/movie/service/MovieServiceTest.java @@ -0,0 +1,90 @@ +package com.example.movie.service; + +import com.example.movie.converter.DtoConverter; +import com.example.movie.dto.MoviesDetailResponse; +import com.example.jpa.entity.movie.Genre; +import com.example.jpa.entity.movie.Grade; +import com.example.jpa.repository.movie.MovieRepository; +import com.example.jpa.repository.movie.dto.MoviesDetailDto; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class MovieServiceTest { + @Mock + private MovieRepository movieRepository; + @Mock + private DtoConverter dtoConvertor; + @InjectMocks + MovieService movieService; + + @Test + @DisplayName("현재 상영중인 영화를 개봉일 순으로 정렬한다..") + void 현재상영중인_영화조회_개봉일순_정렬_성공(){ + //given + LocalDateTime now = LocalDateTime.now(); + List mockDbResults = initMoviesDetailDtoData(now); + List mockConvertedResults = initMoviesDetailData(); + + when(movieRepository.searchWithFiltering(now,null,null)).thenReturn(mockDbResults); + when(dtoConvertor.moviesNowScreening(mockDbResults)).thenReturn(mockConvertedResults); + + //when + List result = movieService.getMovies(now, Boolean.TRUE, null, null); + + //then + assertThat(result.get(0).movieId()).isEqualTo(2L); + assertThat(result.get(1).movieId()).isEqualTo(1L); + } + + private static List initMoviesDetailData() { + List mockConvertedResults = List.of( + new MoviesDetailResponse( + 1L, "Movie A", Grade.ALL_AGE, LocalDate.of(2023, 12, 15), + "thumbnailA.jpg", 120L, Genre.ACTION, List.of() + ), + new MoviesDetailResponse( + 2L, "Movie B", Grade.FROM_12_AGE, LocalDate.of(2024, 1, 10), + "thumbnailB.jpg", 130L, Genre.ROMANCE, List.of() + ) + ); + return mockConvertedResults; + } + + private static List initMoviesDetailDtoData(LocalDateTime now) { + List mockDbResults = List.of( + new MoviesDetailDto( + 1L, "Movie A", Grade.ALL_AGE, LocalDate.of(2023, 12, 15), + "thumbnailA.jpg", 120L, Genre.ACTION, 1L, "Theater 1", + now.plusHours(1), now.plusHours(3) + ), + new MoviesDetailDto( + 1L, "Movie A", Grade.ALL_AGE, LocalDate.of(2023, 12, 15), + "thumbnailA.jpg", 120L, Genre.ACTION, 1L, "Theater 1", + now.plusHours(3), now.plusHours(5) + ), + new MoviesDetailDto( + 1L, "Movie A", Grade.ALL_AGE, LocalDate.of(2023, 12, 15), + "thumbnailA.jpg", 120L, Genre.ACTION, 2L, "Theater 2", + now.plusHours(2), now.plusHours(4) + ), + new MoviesDetailDto( + 2L, "Movie B", Grade.FROM_12_AGE, LocalDate.of(2024, 1, 10), + "thumbnailB.jpg", 130L, Genre.ROMANCE, 1L, "Theater 1", + now.plusHours(3), now.plusHours(5) + ) + ); + return mockDbResults; + } +} \ No newline at end of file diff --git a/domain/src/test/java/com/example/reservation/service/ReservationConcurrencyTest.java b/domain/src/test/java/com/example/reservation/service/ReservationConcurrencyTest.java new file mode 100644 index 000000000..47f570ebb --- /dev/null +++ b/domain/src/test/java/com/example/reservation/service/ReservationConcurrencyTest.java @@ -0,0 +1,66 @@ +package com.example.reservation.service; + +import com.example.jpa.repository.movie.SeatRepository; +import com.example.jpa.repository.reservation.ReservationRepository; +import com.example.reservation.dto.ReservationRequest; +import jakarta.persistence.EntityManager; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import java.util.Arrays; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static org.junit.Assert.assertEquals; + +@SpringBootTest +public class ReservationConcurrencyTest { + + @Autowired + private ReservationService reservationService; + + @Autowired + private SeatRepository seatRepository; + + @Autowired + private ReservationRepository reservationRepository; + + @Autowired + private EntityManager entityManager; + + @Test + void testConcurrencyOnReserveSeat() throws InterruptedException { + int threadCount = 100; // 동시에 실행할 쓰레드 수 + ExecutorService executorService = Executors.newFixedThreadPool(32); + CountDownLatch latch = new CountDownLatch(threadCount); + + for (int i = 1; i <= threadCount; i++) { + final long userId = i; // userId를 final로 할당 + executorService.submit(() -> { + try { + ReservationRequest request = new ReservationRequest( + userId, // 각 쓰레드마다 다른 userId 사용 + 1L, // screeningId + Arrays.asList("A1", "A2") // 예약할 좌석 + ); + reservationService.reserveSeat(request); + } catch (Exception e) { + // 예외 발생 시 로깅 또는 무시 (동시성 문제로 예외가 발생하는지 확인용) + System.err.println("예약 실패: " + e.getMessage()); + } finally { + latch.countDown(); + } + }); + } + + latch.await(); // 모든 쓰레드가 작업을 완료할 때까지 대기 + + + // 예약된 수가 최대 한 번만 발생했는지 확인 + long reservationCount = reservationRepository.count(); + assertEquals(2 , reservationCount); // 동시에 실행했어도 하나의 예약만 성공해야 함 + } + +} diff --git a/domain/src/test/java/com/example/reservation/service/ReservationServiceTest.java b/domain/src/test/java/com/example/reservation/service/ReservationServiceTest.java new file mode 100644 index 000000000..f19928a96 --- /dev/null +++ b/domain/src/test/java/com/example/reservation/service/ReservationServiceTest.java @@ -0,0 +1,103 @@ +package com.example.reservation.service; + +import com.example.jpa.entity.movie.Screening; +import com.example.jpa.entity.theater.Seat; +import com.example.jpa.entity.user.entity.User; +import com.example.jpa.repository.movie.ScreeningRepository; +import com.example.jpa.repository.movie.SeatRepository; +import com.example.jpa.repository.reservation.ReservationRepository; +import com.example.jpa.repository.user.UserRepository; +import com.example.message.MessageService; +import com.example.reservation.dto.ReservationRequest; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.Arrays; +import java.util.Optional; + +import static org.junit.Assert.assertThrows; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class ReservationServiceTest { + + @Mock(lenient = true) + private ScreeningRepository screeningRepository; + + @Mock(lenient = true) + private ReservationRepository reservationRepository; + + @Mock(lenient = true) + private SeatRepository seatRepository; + + @Mock(lenient = true) + private UserRepository userRepository; + + @Mock(lenient = true) + private MessageService messageService; + + @InjectMocks + private ReservationService reservationService; + + private User user; + + private Screening screening; + + private ReservationRequest reservationRequest; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + user = new User(); + screening = new Screening(); + + when(userRepository.findById(1L)).thenReturn(Optional.of(user)); + when(screeningRepository.findById(1L)).thenReturn(Optional.of(screening)); + when(reservationRepository.getReservationCount(1L, 1L)).thenReturn(0L); + } + + @Test + @DisplayName("인접하지 않은 좌석(A1, A3)에 대해 예외가 발생한다.") + void testReserveSeat_SeatsNotAdjacent_A1_A3() { + //given + when(seatRepository.findByPositionAndScreeningId("A1", 1L)).thenReturn(Optional.of(new Seat())); + when(seatRepository.findByPositionAndScreeningId("A3", 1L)).thenReturn(Optional.of(new Seat())); + + reservationRequest = new ReservationRequest(1L, 1L, Arrays.asList("A1", "A3")); + + //when & then + assertThrows(IllegalArgumentException.class, () -> reservationService.reserveSeat(reservationRequest)); + } + + @Test + @DisplayName("인접하지 않은 좌석(A1, B1)에 대해 예외가 발생한다.") + void testReserveSeat_SeatsNotAdjacent_A1_B1() { + //given + when(seatRepository.findByPositionAndScreeningId("A1", 1L)).thenReturn(Optional.of(new Seat())); + when(seatRepository.findByPositionAndScreeningId("B1", 1L)).thenReturn(Optional.of(new Seat())); + + reservationRequest = new ReservationRequest(1L, 1L, Arrays.asList("A1", "B1")); + + //when & then + assertThrows(IllegalArgumentException.class, () -> reservationService.reserveSeat(reservationRequest)); + } + + @Test + @DisplayName("인접한 좌석(A1, A2)에 대해 성공한다.") + void testReserveSeat_SeatsAdjacent() throws InterruptedException { + /** 테스트 실패. 존재하지 않는 좌석이라고 뜸 + * when으로 stub 해줬는데 왜? + */ + when(seatRepository.findByPositionAndScreeningId("A1", 1L)).thenReturn(Optional.of(new Seat())); + when(seatRepository.findByPositionAndScreeningId("A2", 1L)).thenReturn(Optional.of(new Seat())); + + reservationRequest = new ReservationRequest(1L, 1L, Arrays.asList("A1", "A2")); + reservationService.reserveSeat(reservationRequest); + } +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..a4b76b953 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..e2847c820 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 000000000..f5feea6d6 --- /dev/null +++ b/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 000000000..9d21a2183 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/img.png b/img.png new file mode 100644 index 000000000..cda5fc305 Binary files /dev/null and b/img.png differ diff --git a/img_1.png b/img_1.png new file mode 100644 index 000000000..f3ed88f35 Binary files /dev/null and b/img_1.png differ diff --git a/img_2.png b/img_2.png new file mode 100644 index 000000000..f3ed88f35 Binary files /dev/null and b/img_2.png differ diff --git a/img_3.png b/img_3.png new file mode 100644 index 000000000..566fade35 Binary files /dev/null and b/img_3.png differ diff --git a/img_4.png b/img_4.png new file mode 100644 index 000000000..ce0a1b4cc Binary files /dev/null and b/img_4.png differ diff --git a/img_5.png b/img_5.png new file mode 100644 index 000000000..307e32d11 Binary files /dev/null and b/img_5.png differ diff --git a/img_6.png b/img_6.png new file mode 100644 index 000000000..eea9b7b16 Binary files /dev/null and b/img_6.png differ diff --git a/img_7.png b/img_7.png new file mode 100644 index 000000000..4cc00c445 Binary files /dev/null and b/img_7.png differ diff --git a/img_8.png b/img_8.png new file mode 100644 index 000000000..db953e8e5 Binary files /dev/null and b/img_8.png differ diff --git a/img_9.png b/img_9.png new file mode 100644 index 000000000..e1b4ee443 Binary files /dev/null and b/img_9.png differ diff --git a/infra/build.gradle b/infra/build.gradle new file mode 100644 index 000000000..208006f2f --- /dev/null +++ b/infra/build.gradle @@ -0,0 +1,48 @@ +buildscript { + ext { + queryDslVersion = "5.0.0" + } +} + +plugins { + id 'com.ewerk.gradle.plugins.querydsl' version '1.0.10' +} + +bootJar.enabled = false + +jar.enabled = true + +dependencies { + api 'org.springframework.boot:spring-boot-starter-cache' + api 'com.github.ben-manes.caffeine:caffeine' + api("org.springframework.boot:spring-boot-starter-data-redis") + api("org.redisson:redisson-spring-boot-starter:3.17.0:") + + implementation "com.querydsl:querydsl-jpa:${queryDslVersion}:jakarta" + implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.15.2' + annotationProcessor "com.querydsl:querydsl-apt:${queryDslVersion}:jakarta" + annotationProcessor "jakarta.annotation:jakarta.annotation-api" + annotationProcessor "jakarta.persistence:jakarta.persistence-api" + + runtimeOnly 'com.mysql:mysql-connector-j' + api("org.springframework.boot:spring-boot-starter-data-jpa") +} + +def querydslDir = "$buildDir/generated/querydsl" + +querydsl { + jpa = true + querydslSourcesDir = querydslDir +} +sourceSets { + main.java.srcDir querydslDir +} +compileQuerydsl{ + options.annotationProcessorPath = configurations.querydsl +} +configurations { + compileOnly { + extendsFrom annotationProcessor + } + querydsl.extendsFrom compileClasspath +} \ No newline at end of file diff --git a/infra/src/main/java/com/example/jpa/JpaAuditingConfig.java b/infra/src/main/java/com/example/jpa/JpaAuditingConfig.java new file mode 100644 index 000000000..5b3594bc9 --- /dev/null +++ b/infra/src/main/java/com/example/jpa/JpaAuditingConfig.java @@ -0,0 +1,9 @@ +package com.example.jpa; + +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +@Configuration +@EnableJpaAuditing +public class JpaAuditingConfig { +} diff --git a/infra/src/main/java/com/example/jpa/entity/BaseEntity.java b/infra/src/main/java/com/example/jpa/entity/BaseEntity.java new file mode 100644 index 000000000..8709b7e27 --- /dev/null +++ b/infra/src/main/java/com/example/jpa/entity/BaseEntity.java @@ -0,0 +1,37 @@ +package com.example.jpa.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.MappedSuperclass; +import lombok.Data; +import org.springframework.data.annotation.CreatedBy; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedBy; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.LocalDateTime; + +@Data +@EntityListeners(AuditingEntityListener.class) +@MappedSuperclass +public abstract class BaseEntity { + + @CreatedDate + @Column(updatable = false) + private LocalDateTime createAt; + + + @LastModifiedDate + private LocalDateTime modifyAt; + + + @CreatedBy + @Column(updatable = false) + private String createBy; + + + @LastModifiedBy + private String modifyBy; + +} diff --git a/infra/src/main/java/com/example/jpa/entity/movie/Genre.java b/infra/src/main/java/com/example/jpa/entity/movie/Genre.java new file mode 100644 index 000000000..4d8a371a7 --- /dev/null +++ b/infra/src/main/java/com/example/jpa/entity/movie/Genre.java @@ -0,0 +1,5 @@ +package com.example.jpa.entity.movie; + +public enum Genre { + ACTION, ROMANCE, HORROR, SF +} diff --git a/infra/src/main/java/com/example/jpa/entity/movie/Grade.java b/infra/src/main/java/com/example/jpa/entity/movie/Grade.java new file mode 100644 index 000000000..98fe06fd6 --- /dev/null +++ b/infra/src/main/java/com/example/jpa/entity/movie/Grade.java @@ -0,0 +1,5 @@ +package com.example.jpa.entity.movie; + +public enum Grade { + ALL_AGE, FROM_12_AGE, FROM_15_AGE, FROM_19_AGE, RESTRICTED +} diff --git a/infra/src/main/java/com/example/jpa/entity/movie/Movie.java b/infra/src/main/java/com/example/jpa/entity/movie/Movie.java new file mode 100644 index 000000000..d5fb0aec8 --- /dev/null +++ b/infra/src/main/java/com/example/jpa/entity/movie/Movie.java @@ -0,0 +1,28 @@ +package com.example.jpa.entity.movie; + +import com.example.jpa.entity.BaseEntity; +import jakarta.persistence.*; + +import java.time.LocalDate; + +@Entity +public class Movie extends BaseEntity { + + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String name; + + private String thumbnail; + + @Enumerated(EnumType.STRING) + private Genre genre; + + @Enumerated(EnumType.STRING) + private Grade grade; + + private LocalDate releaseDate; + + private Long runningTime; + +} diff --git a/infra/src/main/java/com/example/jpa/entity/movie/Screening.java b/infra/src/main/java/com/example/jpa/entity/movie/Screening.java new file mode 100644 index 000000000..6f639f8b3 --- /dev/null +++ b/infra/src/main/java/com/example/jpa/entity/movie/Screening.java @@ -0,0 +1,28 @@ +package com.example.jpa.entity.movie; + +import com.example.jpa.entity.BaseEntity; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import lombok.Getter; + +import java.time.LocalDateTime; + +@Entity +@Getter +public class Screening extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private Long movieId; + + private Long theaterId; + + private LocalDateTime startAt; + + private LocalDateTime endAt; + +} diff --git a/infra/src/main/java/com/example/jpa/entity/reservation/Reservation.java b/infra/src/main/java/com/example/jpa/entity/reservation/Reservation.java new file mode 100644 index 000000000..d3aed16dd --- /dev/null +++ b/infra/src/main/java/com/example/jpa/entity/reservation/Reservation.java @@ -0,0 +1,26 @@ +package com.example.jpa.entity.reservation; + +import com.example.jpa.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.Getter; + +@Entity +@Getter +public class Reservation extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private Long userId; + + private Long seatId; + + private Long screeningId; + + public void reserve(Long userId, Long seatId, Long screeningId) { + this.userId = userId; + this.seatId = seatId; + this.screeningId = screeningId; + } +} diff --git a/infra/src/main/java/com/example/jpa/entity/theater/Seat.java b/infra/src/main/java/com/example/jpa/entity/theater/Seat.java new file mode 100644 index 000000000..b46e5971e --- /dev/null +++ b/infra/src/main/java/com/example/jpa/entity/theater/Seat.java @@ -0,0 +1,22 @@ +package com.example.jpa.entity.theater; + +import com.example.jpa.entity.BaseEntity; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import lombok.Getter; + +@Entity +@Getter +public class Seat extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private Long theaterId; + + private String position; + +} diff --git a/infra/src/main/java/com/example/jpa/entity/theater/Theater.java b/infra/src/main/java/com/example/jpa/entity/theater/Theater.java new file mode 100644 index 000000000..474fb3155 --- /dev/null +++ b/infra/src/main/java/com/example/jpa/entity/theater/Theater.java @@ -0,0 +1,18 @@ +package com.example.jpa.entity.theater; + +import com.example.jpa.entity.BaseEntity; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; + +@Entity +public class Theater extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String name; + +} diff --git a/infra/src/main/java/com/example/jpa/entity/user/entity/User.java b/infra/src/main/java/com/example/jpa/entity/user/entity/User.java new file mode 100644 index 000000000..e6f4afcee --- /dev/null +++ b/infra/src/main/java/com/example/jpa/entity/user/entity/User.java @@ -0,0 +1,20 @@ +package com.example.jpa.entity.user.entity; + +import com.example.jpa.entity.BaseEntity; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import lombok.Getter; + +@Entity +@Getter +public class User extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String name; + +} diff --git a/infra/src/main/java/com/example/jpa/repository/movie/MovieRepository.java b/infra/src/main/java/com/example/jpa/repository/movie/MovieRepository.java new file mode 100644 index 000000000..6f1193e1c --- /dev/null +++ b/infra/src/main/java/com/example/jpa/repository/movie/MovieRepository.java @@ -0,0 +1,8 @@ +package com.example.jpa.repository.movie; + +import com.example.jpa.entity.movie.Movie; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface MovieRepository extends JpaRepository, MovieRepositoryCustom { + +} diff --git a/infra/src/main/java/com/example/jpa/repository/movie/MovieRepositoryCustom.java b/infra/src/main/java/com/example/jpa/repository/movie/MovieRepositoryCustom.java new file mode 100644 index 000000000..d03197c7c --- /dev/null +++ b/infra/src/main/java/com/example/jpa/repository/movie/MovieRepositoryCustom.java @@ -0,0 +1,11 @@ +package com.example.jpa.repository.movie; + +import com.example.jpa.entity.movie.Genre; +import com.example.jpa.repository.movie.dto.MoviesDetailDto; + +import java.time.LocalDateTime; +import java.util.List; + +public interface MovieRepositoryCustom { + List searchWithFiltering(LocalDateTime now, Genre genre, String title); +} diff --git a/infra/src/main/java/com/example/jpa/repository/movie/MovieRepositoryImpl.java b/infra/src/main/java/com/example/jpa/repository/movie/MovieRepositoryImpl.java new file mode 100644 index 000000000..ecd08d287 --- /dev/null +++ b/infra/src/main/java/com/example/jpa/repository/movie/MovieRepositoryImpl.java @@ -0,0 +1,65 @@ +package com.example.jpa.repository.movie; + +import com.example.jpa.entity.movie.Genre; +import com.example.jpa.entity.movie.QMovie; +import com.example.jpa.entity.movie.QScreening; +import com.example.jpa.repository.movie.dto.MoviesDetailDto; +import com.example.jpa.repository.movie.dto.QMoviesDetailDto; +import com.querydsl.core.types.dsl.BooleanExpression; +import com.querydsl.jpa.impl.JPAQueryFactory; +import jakarta.persistence.EntityManager; + +import java.time.LocalDateTime; +import java.util.List; + +import static com.example.jpa.entity.movie.QMovie.movie; +import static com.example.jpa.entity.movie.QScreening.screening; +import static com.example.jpa.entity.theater.QTheater.theater; + +public class MovieRepositoryImpl implements MovieRepositoryCustom{ + + private final JPAQueryFactory queryFactory; + + public MovieRepositoryImpl(EntityManager em) { + this.queryFactory = new JPAQueryFactory(em); + } + + @Override + public List searchWithFiltering(LocalDateTime now, Genre genre, String title) { + return queryFactory + .select(new QMoviesDetailDto( + movie.id, + movie.name, + movie.grade, + movie.releaseDate, + movie.thumbnail, + movie.runningTime, + movie.genre, + theater.id, + theater.name, + screening.startAt, + screening.endAt + )) + .from(movie) + .join(screening).on(movie.id.eq(screening.movieId)) + .join(theater).on(screening.theaterId.eq(theater.id)) + .where( + startAtAfter(now), + genreEquals(genre), + nameContains(title) + ) + .fetch(); + } + + private BooleanExpression startAtAfter(LocalDateTime now) { + return now != null ? QScreening.screening.startAt.goe(now) : null; + } + + private BooleanExpression genreEquals(Genre genre) { + return genre != null ? QMovie.movie.genre.eq(genre) : null; + } + + private BooleanExpression nameContains(String title) { + return title != null ? QMovie.movie.name.containsIgnoreCase(title) : null; + } +} diff --git a/infra/src/main/java/com/example/jpa/repository/movie/ScreeningRepository.java b/infra/src/main/java/com/example/jpa/repository/movie/ScreeningRepository.java new file mode 100644 index 000000000..18182797b --- /dev/null +++ b/infra/src/main/java/com/example/jpa/repository/movie/ScreeningRepository.java @@ -0,0 +1,7 @@ +package com.example.jpa.repository.movie; + +import com.example.jpa.entity.movie.Screening; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ScreeningRepository extends JpaRepository { +} diff --git a/infra/src/main/java/com/example/jpa/repository/movie/SeatRepository.java b/infra/src/main/java/com/example/jpa/repository/movie/SeatRepository.java new file mode 100644 index 000000000..08fde2223 --- /dev/null +++ b/infra/src/main/java/com/example/jpa/repository/movie/SeatRepository.java @@ -0,0 +1,21 @@ +package com.example.jpa.repository.movie; + +import com.example.jpa.entity.theater.Seat; +import jakarta.persistence.LockModeType; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Lock; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.Optional; + +public interface SeatRepository extends JpaRepository { + + @Query("SELECT s FROM Seat s " + + "JOIN Theater t ON s.theaterId = t.id " + + "JOIN Screening sc ON sc.theaterId = t.id " + + "WHERE s.position = :position AND sc.id = :screeningId") + Optional findByPositionAndScreeningId(@Param("position") String position, + @Param("screeningId") Long screeningId); + +} diff --git a/infra/src/main/java/com/example/jpa/repository/movie/dto/MoviesDetailDto.java b/infra/src/main/java/com/example/jpa/repository/movie/dto/MoviesDetailDto.java new file mode 100644 index 000000000..cda7667ef --- /dev/null +++ b/infra/src/main/java/com/example/jpa/repository/movie/dto/MoviesDetailDto.java @@ -0,0 +1,41 @@ +package com.example.jpa.repository.movie.dto; + +import com.example.jpa.entity.movie.Genre; +import com.example.jpa.entity.movie.Grade; +import com.querydsl.core.annotations.QueryProjection; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +@Getter +@NoArgsConstructor +public class MoviesDetailDto { + private Long movieId; + private String movieName; + private Grade grade; + private LocalDate releaseDate; + private String thumbnail; + private Long runningTime; + private Genre genre; + private Long theaterId; + private String theaterName; + private LocalDateTime startAt; + private LocalDateTime endAt; + + @QueryProjection + public MoviesDetailDto(Long movieId, String movieName, Grade grade, LocalDate releaseDate, String thumbnail, Long runningTime, Genre genre, Long theaterId, String theaterName, LocalDateTime startAt, LocalDateTime endAt) { + this.movieId = movieId; + this.movieName = movieName; + this.grade = grade; + this.releaseDate = releaseDate; + this.thumbnail = thumbnail; + this.runningTime = runningTime; + this.genre = genre; + this.theaterId = theaterId; + this.theaterName = theaterName; + this.startAt = startAt; + this.endAt = endAt; + } +} diff --git a/infra/src/main/java/com/example/jpa/repository/reservation/ReservationRepository.java b/infra/src/main/java/com/example/jpa/repository/reservation/ReservationRepository.java new file mode 100644 index 000000000..39af228b6 --- /dev/null +++ b/infra/src/main/java/com/example/jpa/repository/reservation/ReservationRepository.java @@ -0,0 +1,18 @@ +package com.example.jpa.repository.reservation; + +import com.example.jpa.entity.reservation.Reservation; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface ReservationRepository extends JpaRepository { + + @Query("SELECT COUNT(r) FROM Reservation r " + + "JOIN Seat s ON s.id = r.seatId " + + "JOIN Screening sc ON sc.id = r.screeningId " + + "WHERE r.userId = :userId AND sc.id = :screeningId") + Long getReservationCount(@Param("userId") Long userId, @Param("screeningId") Long screeningId); + + boolean existsBySeatIdAndScreeningId(Long seatId, Long screeningId); + +} diff --git a/infra/src/main/java/com/example/jpa/repository/user/UserRepository.java b/infra/src/main/java/com/example/jpa/repository/user/UserRepository.java new file mode 100644 index 000000000..e0b989911 --- /dev/null +++ b/infra/src/main/java/com/example/jpa/repository/user/UserRepository.java @@ -0,0 +1,7 @@ +package com.example.jpa.repository.user; + +import com.example.jpa.entity.user.entity.User; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { +} diff --git a/infra/src/main/java/com/example/redis/CacheConfig.java b/infra/src/main/java/com/example/redis/CacheConfig.java new file mode 100644 index 000000000..fffbeb307 --- /dev/null +++ b/infra/src/main/java/com/example/redis/CacheConfig.java @@ -0,0 +1,74 @@ + +package com.example.redis; + +import com.example.jpa.repository.movie.dto.MoviesDetailDto; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.cache.RedisCacheConfiguration; +import org.springframework.data.redis.cache.RedisCacheManager; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.RedisSerializationContext; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +import java.time.Duration; +import java.util.List; + + +@EnableCaching +@Configuration +public class CacheConfig { + + @Bean + public ObjectMapper objectMapper() { + return new ObjectMapper() + .findAndRegisterModules() + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .registerModule(new JavaTimeModule()); + } + + @Bean + public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory, ObjectMapper objectMapper) { + Jackson2JsonRedisSerializer> serializer = + new Jackson2JsonRedisSerializer<>(objectMapper,objectMapper.getTypeFactory() + .constructCollectionType(List.class, MoviesDetailDto.class)); + + RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration + .defaultCacheConfig() + .serializeKeysWith( + RedisSerializationContext.SerializationPair.fromSerializer( + new StringRedisSerializer())) + .serializeValuesWith( + RedisSerializationContext.SerializationPair.fromSerializer(serializer)) + .entryTtl(Duration.ofMinutes(5L)); + + return RedisCacheManager + .RedisCacheManagerBuilder + .fromConnectionFactory(redisConnectionFactory) + .cacheDefaults(redisCacheConfiguration) + .build(); + } + + + +// @Bean +// public Caffeine caffeineConfig() { +// return Caffeine.newBuilder().expireAfterWrite(5, TimeUnit.MINUTES); +// } +// +// @Bean +// public CacheManager cacheManager(Caffeine caffeine) { +// CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager(); +// caffeineCacheManager.setCaffeine(caffeine); +// +// return caffeineCacheManager; +// } + +} diff --git a/infra/src/main/java/com/example/redis/CustomSpringELParser.java b/infra/src/main/java/com/example/redis/CustomSpringELParser.java new file mode 100644 index 000000000..e8805a91c --- /dev/null +++ b/infra/src/main/java/com/example/redis/CustomSpringELParser.java @@ -0,0 +1,21 @@ +package com.example.redis; + +import org.springframework.expression.ExpressionParser; +import org.springframework.expression.spel.standard.SpelExpressionParser; +import org.springframework.expression.spel.support.StandardEvaluationContext; + +public class CustomSpringELParser { + private CustomSpringELParser() { + } + + public static Object getDynamicValue(String[] parameterNames, Object[] args, String key) { + ExpressionParser parser = new SpelExpressionParser(); + StandardEvaluationContext context = new StandardEvaluationContext(); + + for (int i = 0; i < parameterNames.length; i++) { + context.setVariable(parameterNames[i], args[i]); + } + + return parser.parseExpression(key).getValue(context, Object.class); + } +} diff --git a/infra/src/main/java/com/example/redis/DistributedLock.java b/infra/src/main/java/com/example/redis/DistributedLock.java new file mode 100644 index 000000000..dab675686 --- /dev/null +++ b/infra/src/main/java/com/example/redis/DistributedLock.java @@ -0,0 +1,34 @@ +package com.example.redis; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.util.concurrent.TimeUnit; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface DistributedLock { + /** + * 락의 이름 + */ + String key(); + + /** + * 락의 시간 단위 + */ + TimeUnit timeUnit() default TimeUnit.SECONDS; + + /** + * 락을 기다리는 시간 (default - 5초) + * 락 획득을 위해 waitTime 만큼 대기한다 + */ + long waitTime() default 5L; + + /** + * 락 임대 시간 (default - 3초) + * 락을 획득한 이후 leaseTime 이 지나면 락을 해제한다 + */ + long leaseTime() default 3L; +} + diff --git a/infra/src/main/java/com/example/redis/DistributedLockAop.java b/infra/src/main/java/com/example/redis/DistributedLockAop.java new file mode 100644 index 000000000..858008ce7 --- /dev/null +++ b/infra/src/main/java/com/example/redis/DistributedLockAop.java @@ -0,0 +1,43 @@ +package com.example.redis; + +import lombok.RequiredArgsConstructor; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.reflect.MethodSignature; +import org.redisson.api.RLock; +import org.redisson.api.RedissonClient; +import org.springframework.stereotype.Component; + +@Aspect +@Component +@RequiredArgsConstructor +public class DistributedLockAop { + private static final String REDISSON_LOCK_PREFIX = "LOCK:"; + + private final RedissonClient redissonClient; + + private final RedisLockTransaction redisLockTransaction; + + @Around("@annotation(com.example.redis.DistributedLock)") + public Object lock(final ProceedingJoinPoint joinPoint) throws Throwable { + MethodSignature signature = (MethodSignature) joinPoint.getSignature(); + DistributedLock distributedLock = signature.getMethod().getAnnotation(DistributedLock.class); + + String key = REDISSON_LOCK_PREFIX + CustomSpringELParser.getDynamicValue(signature.getParameterNames(), joinPoint.getArgs(), distributedLock.key()); + RLock rLock = redissonClient.getLock(key); + + try { + boolean available = rLock.tryLock(distributedLock.waitTime(), distributedLock.leaseTime(), distributedLock.timeUnit()); + if (!available) { + return false; + } + return redisLockTransaction.proceed(joinPoint); + } catch (InterruptedException e) { + throw new InterruptedException(); + } finally { + rLock.unlock(); + } + } + +} diff --git a/infra/src/main/java/com/example/redis/DistributedLockService.java b/infra/src/main/java/com/example/redis/DistributedLockService.java new file mode 100644 index 000000000..88219f0bd --- /dev/null +++ b/infra/src/main/java/com/example/redis/DistributedLockService.java @@ -0,0 +1,47 @@ +package com.example.redis; + +import lombok.RequiredArgsConstructor; +import org.redisson.RedissonMultiLock; +import org.redisson.api.RLock; +import org.redisson.api.RedissonClient; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +@Component +@RequiredArgsConstructor +public class DistributedLockService { + private final RedissonClient redissonClient; + + private final RedisLockTransaction redisLockTransaction; + + public T executeWithLockAndReturn(Supplier action, Long screeningId, List seatIds, long waitTime, long leaseTime) throws InterruptedException { + + List locks = seatIds.stream() + .map(seatId -> redissonClient.getLock("lock:screening:" + screeningId + ":seat:" + seatId)) + .collect(Collectors.toList()); + + RLock multiLock = new RedissonMultiLock(locks.toArray(new RLock[0])); + + boolean lockAcquired = false; + + try { + lockAcquired = multiLock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS); + + if (!lockAcquired) { + throw new IllegalStateException("락을 획득할 수 없습니다."); + } + + return redisLockTransaction.execute(action); + + } finally { + if (lockAcquired) { + multiLock.unlock(); // 모든 락 해제 + } + } + } + +} diff --git a/infra/src/main/java/com/example/redis/RedisConfig.java b/infra/src/main/java/com/example/redis/RedisConfig.java new file mode 100644 index 000000000..927a97d1e --- /dev/null +++ b/infra/src/main/java/com/example/redis/RedisConfig.java @@ -0,0 +1,36 @@ +package com.example.redis; + +import org.redisson.Redisson; +import org.redisson.api.RedissonClient; +import org.redisson.config.Config; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisStandaloneConfiguration; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; + +@Configuration +public class RedisConfig { + @Value("${spring.data.redis.host}") + private String host; + + @Value("${spring.data.redis.port}") + private int port; + + private static final String REDISSON_HOST_PREFIX = "redis://"; + + @Bean + public LettuceConnectionFactory redisConnectionFactory() { + // Lettuce라는 라이브러리를 활용해 Redis 연결을 관리하는 객체를 생성하고 + // Redis 서버에 대한 정보(host, port)를 설정한다. + return new LettuceConnectionFactory(new RedisStandaloneConfiguration(host, port)); + } + + @Bean + public RedissonClient redissonClient() { + Config config = new Config(); + config.useSingleServer().setAddress(REDISSON_HOST_PREFIX + "localhost:6379"); + return Redisson.create(config); + } + +} diff --git a/infra/src/main/java/com/example/redis/RedisLockTransaction.java b/infra/src/main/java/com/example/redis/RedisLockTransaction.java new file mode 100644 index 000000000..453d643d7 --- /dev/null +++ b/infra/src/main/java/com/example/redis/RedisLockTransaction.java @@ -0,0 +1,21 @@ +package com.example.redis; + +import org.aspectj.lang.ProceedingJoinPoint; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.util.function.Supplier; + +@Component +public class RedisLockTransaction { + @Transactional(propagation = Propagation.REQUIRES_NEW) + public Object proceed(final ProceedingJoinPoint joinPoint) throws Throwable { + return joinPoint.proceed(); + } + + @Transactional(propagation = Propagation.REQUIRES_NEW) + public T execute(Supplier action) { + return action.get(); + } +} diff --git a/infra/src/main/resources/application.yml b/infra/src/main/resources/application.yml new file mode 100644 index 000000000..1562c949d --- /dev/null +++ b/infra/src/main/resources/application.yml @@ -0,0 +1,28 @@ +spring: + datasource: + url: jdbc:mysql://localhost:3305/hanghae99 + username: root + password: 1234 + driver-class-name: com.mysql.cj.jdbc.Driver + jpa: + defer-datasource-initialization: true + hibernate: + ddl-auto: update + properties: + hibernate: + format_sql: true + show_sql: true + data: + redis: + host: localhost + port: 6378 + sql: + init: + data-locations: classpath:data.sql + platform: mysql + mode: never + +logging: + level: + org.springframework.cache: trace + diff --git a/infra/src/main/resources/data.sql b/infra/src/main/resources/data.sql new file mode 100644 index 000000000..0ddcdaf8a --- /dev/null +++ b/infra/src/main/resources/data.sql @@ -0,0 +1,212 @@ +SET SESSION cte_max_recursion_depth = 1000000; + +DELETE FROM screening; +DELETE FROM movie; +DELETE FROM theater; +DELETE FROM user; +DELETE FROM reservation; + +-- 상영관 데이터 삽입 +INSERT INTO theater (id, name, create_at, modify_at) +VALUES + (1, '상영관 1관', NOW(), NOW()), + (2, '상영관 2관', NOW(), NOW()), + (3, '상영관 3관', NOW(), NOW()); + + +INSERT INTO user (id, name, create_at, modify_at) +VALUES + (1, '유저 1', NOW(), NOW()), + (2, '유저 2', NOW(), NOW()), + (3, '유저 3', NOW(), NOW()), + (4, '유저 4', NOW(), NOW()), + (5, '유저 5', NOW(), NOW()), + (6, '유저 6', NOW(), NOW()), + (7, '유저 7', NOW(), NOW()), + (8, '유저 8', NOW(), NOW()), + (9, '유저 9', NOW(), NOW()), + (10, '유저 10', NOW(), NOW()), + (11, '유저 11', NOW(), NOW()), + (12, '유저 12', NOW(), NOW()), + (13, '유저 13', NOW(), NOW()), + (14, '유저 14', NOW(), NOW()), + (15, '유저 15', NOW(), NOW()), + (16, '유저 16', NOW(), NOW()), + (17, '유저 17', NOW(), NOW()), + (18, '유저 18', NOW(), NOW()), + (19, '유저 19', NOW(), NOW()), + (20, '유저 20', NOW(), NOW()), + (21, '유저 21', NOW(), NOW()), + (22, '유저 22', NOW(), NOW()), + (23, '유저 23', NOW(), NOW()), + (24, '유저 24', NOW(), NOW()), + (25, '유저 25', NOW(), NOW()), + (26, '유저 26', NOW(), NOW()), + (27, '유저 27', NOW(), NOW()), + (28, '유저 28', NOW(), NOW()), + (29, '유저 29', NOW(), NOW()), + (30, '유저 30', NOW(), NOW()), + (31, '유저 31', NOW(), NOW()), + (32, '유저 32', NOW(), NOW()), + (33, '유저 33', NOW(), NOW()), + (34, '유저 34', NOW(), NOW()), + (35, '유저 35', NOW(), NOW()), + (36, '유저 36', NOW(), NOW()), + (37, '유저 37', NOW(), NOW()), + (38, '유저 38', NOW(), NOW()), + (39, '유저 39', NOW(), NOW()), + (40, '유저 40', NOW(), NOW()), + (41, '유저 41', NOW(), NOW()), + (42, '유저 42', NOW(), NOW()), + (43, '유저 43', NOW(), NOW()), + (44, '유저 44', NOW(), NOW()), + (45, '유저 45', NOW(), NOW()), + (46, '유저 46', NOW(), NOW()), + (47, '유저 47', NOW(), NOW()), + (48, '유저 48', NOW(), NOW()), + (49, '유저 49', NOW(), NOW()), + (50, '유저 50', NOW(), NOW()), + (51, '유저 51', NOW(), NOW()), + (52, '유저 52', NOW(), NOW()), + (53, '유저 53', NOW(), NOW()), + (54, '유저 54', NOW(), NOW()), + (55, '유저 55', NOW(), NOW()), + (56, '유저 56', NOW(), NOW()), + (57, '유저 57', NOW(), NOW()), + (58, '유저 58', NOW(), NOW()), + (59, '유저 59', NOW(), NOW()), + (60, '유저 60', NOW(), NOW()), + (61, '유저 61', NOW(), NOW()), + (62, '유저 62', NOW(), NOW()), + (63, '유저 63', NOW(), NOW()), + (64, '유저 64', NOW(), NOW()), + (65, '유저 65', NOW(), NOW()), + (66, '유저 66', NOW(), NOW()), + (67, '유저 67', NOW(), NOW()), + (68, '유저 68', NOW(), NOW()), + (69, '유저 69', NOW(), NOW()), + (70, '유저 70', NOW(), NOW()), + (71, '유저 71', NOW(), NOW()), + (72, '유저 72', NOW(), NOW()), + (73, '유저 73', NOW(), NOW()), + (74, '유저 74', NOW(), NOW()), + (75, '유저 75', NOW(), NOW()), + (76, '유저 76', NOW(), NOW()), + (77, '유저 77', NOW(), NOW()), + (78, '유저 78', NOW(), NOW()), + (79, '유저 79', NOW(), NOW()), + (80, '유저 80', NOW(), NOW()), + (81, '유저 81', NOW(), NOW()), + (82, '유저 82', NOW(), NOW()), + (83, '유저 83', NOW(), NOW()), + (84, '유저 84', NOW(), NOW()), + (85, '유저 85', NOW(), NOW()), + (86, '유저 86', NOW(), NOW()), + (87, '유저 87', NOW(), NOW()), + (88, '유저 88', NOW(), NOW()), + (89, '유저 89', NOW(), NOW()), + (90, '유저 90', NOW(), NOW()), + (91, '유저 91', NOW(), NOW()), + (92, '유저 92', NOW(), NOW()), + (93, '유저 93', NOW(), NOW()), + (94, '유저 94', NOW(), NOW()), + (95, '유저 95', NOW(), NOW()), + (96, '유저 96', NOW(), NOW()), + (97, '유저 97', NOW(), NOW()), + (98, '유저 98', NOW(), NOW()), + (99, '유저 99', NOW(), NOW()), + (100, '유저 100', NOW(), NOW()); + +-- movies 테이블에 데이터 삽입 +INSERT INTO movie (id, name, thumbnail, genre, grade, release_date, running_time, create_at, modify_at) +WITH RECURSIVE cte (n) AS ( + SELECT 1 + UNION ALL + SELECT n + 1 FROM cte WHERE n < 500 -- 생성할 영화 개수 +) +SELECT + n AS id, + CONCAT('Movie ', LPAD(n, 3, '0')) AS name, + NULL AS thumbnail, + CASE MOD(n, 4) + WHEN 0 THEN 'ACTION' + WHEN 1 THEN 'ROMANCE' + WHEN 2 THEN 'HORROR' + WHEN 3 THEN 'SF' + END AS genre, + CASE MOD(n, 5) + WHEN 0 THEN 'FROM_12_AGE' + WHEN 1 THEN 'FROM_15_AGE' + WHEN 2 THEN 'FROM_19_AGE' + WHEN 3 THEN 'ALL_AGE' + WHEN 4 THEN 'RESTRICTED' + END AS grade, + DATE_SUB(CURRENT_DATE, INTERVAL FLOOR(RAND() * 100 + n) DAY) AS release_date, + MOD(n, 120) + 60 AS running_time, + NOW() AS create_at, + NOW() AS modify_at +FROM cte; + +-- screenings 테이블에 상영 일정 데이터 삽입 +INSERT INTO screening (movie_id, theater_id, start_at, end_at, create_at, modify_at) +WITH RECURSIVE cte (movie_id, schedule_number) AS ( + SELECT 1, 1 + UNION ALL + SELECT + CASE WHEN schedule_number = 6 THEN movie_id + 1 ELSE movie_id END, + CASE WHEN schedule_number = 6 THEN 1 ELSE schedule_number + 1 END + FROM cte + WHERE movie_id <= 500 AND (schedule_number < 6 OR movie_id < 500) +) +SELECT + movie_id, + MOD(schedule_number - 1, 3) + 1 AS theater_id, -- 1~3 순환 + CASE + WHEN MOD(schedule_number, 2) = 0 THEN DATE_ADD(CURRENT_DATE, INTERVAL (schedule_number * 3) HOUR) + ELSE DATE_SUB(CURRENT_DATE, INTERVAL (schedule_number * 3) HOUR) + END AS start_at, + CASE + WHEN MOD(schedule_number, 2) = 0 THEN DATE_ADD(CURRENT_DATE, INTERVAL (schedule_number * 3 + 2) HOUR) + ELSE DATE_SUB(CURRENT_DATE, INTERVAL (schedule_number * 3 - 2) HOUR) + END AS end_at, + NOW() AS create_at, + NOW() AS modify_at +FROM cte +WHERE schedule_number < 6 + OR movie_id < 500; + +INSERT INTO seat (id, theater_id, position, create_at, modify_at) +WITH RECURSIVE seat_cte (seat_id, theater_id, row_name, col_number) AS ( + -- 초기 값: 첫 좌석 데이터 + SELECT + 1 AS seat_id, -- 좌석 ID 시작값 + 1 AS theater_id, -- 상영관 ID 시작값 + 'A' AS row_name, -- 첫 행 + 1 AS col_number -- 첫 열 + UNION ALL + -- 재귀적으로 다음 좌석을 생성 + SELECT + seat_id + 1, -- 다음 좌석 ID + CASE WHEN col_number = 5 AND row_name = 'E' THEN theater_id + 1 -- 마지막 열, 마지막 행이면 다음 상영관 + ELSE theater_id -- 그렇지 않으면 같은 상영관 + END, + CASE WHEN col_number = 5 THEN -- 마지막 열이면 + CASE WHEN row_name = 'E' THEN 'A' -- 마지막 행이면 첫 행으로 + ELSE CHAR(ASCII(row_name) + 1) -- 다음 행 + END + ELSE row_name -- 같은 행 유지 + END, + CASE WHEN col_number = 5 THEN 1 -- 마지막 열이면 첫 열로 + ELSE col_number + 1 -- 다음 열 + END + FROM seat_cte + WHERE theater_id <= 3 -- 상영관 3개까지만 생성 +) +-- 실제 데이터 삽입 +SELECT + seat_id, -- 좌석 ID + theater_id, -- 상영관 ID + CONCAT(row_name, col_number) AS position, -- 좌석 번호 (예: A1, B3 등) + NOW() AS create_at, -- 생성 시각 + NOW() AS modify_at -- 수정 시각 +FROM seat_cte; \ No newline at end of file diff --git a/infra/src/test/java/com/example/TestConfiguration.java b/infra/src/test/java/com/example/TestConfiguration.java new file mode 100644 index 000000000..4fb93008e --- /dev/null +++ b/infra/src/test/java/com/example/TestConfiguration.java @@ -0,0 +1,14 @@ +package com.example; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class TestConfiguration { + + @Test + void contextLoads(){ + + } + +} \ No newline at end of file diff --git a/infra/src/test/java/com/example/movie/repository/MovieRepositoryTest.java b/infra/src/test/java/com/example/movie/repository/MovieRepositoryTest.java new file mode 100644 index 000000000..fa504afa5 --- /dev/null +++ b/infra/src/test/java/com/example/movie/repository/MovieRepositoryTest.java @@ -0,0 +1,83 @@ +package com.example.movie.repository; + +import com.example.TestConfiguration; +import com.example.jpa.repository.movie.MovieRepository; +import com.example.jpa.entity.movie.Genre; +import com.example.jpa.repository.movie.dto.MoviesDetailDto; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.ContextConfiguration; + +import java.time.LocalDateTime; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@ContextConfiguration(classes = TestConfiguration.class) +@DataJpaTest +class MovieRepositoryTest { + + @Autowired + private MovieRepository movieRepository; + + @Test + @DisplayName("장르가 null이고 search가 파일인 경우 현재 상영중인 영화를 성공적으로 조회한다.") + void 장르_null_search_파일_현재상영중인_영화조회_성공(){ + // given + LocalDateTime now = LocalDateTime.now(); + String search = "파일"; + + // when + List result = movieRepository.searchWithFiltering(now, null, search); + + // then + assertThat(result).isNotEmpty(); + assertThat(result).allMatch(movie -> movie.getMovieName().contains("파일")); + } + + @Test + @DisplayName("장르가 SF이고 search가 null인 경우 현재 상영중인 영화를 성공적으로 조회한다.") + void 장르_SF_search_null_현재상영중인_영화조회_성공(){ + // given + LocalDateTime now = LocalDateTime.now(); + Genre genre = Genre.SF; + + // when + List result = movieRepository.searchWithFiltering(now, genre, null); + + // then + assertThat(result).isNotEmpty(); + assertThat(result).allMatch(movie -> movie.getGenre().equals(Genre.SF)); + } + + @Test + @DisplayName("장르가 SF이고 search가 파일인 경우 현재 상영중인 영화를 성공적으로 조회한다.") + void 장르_SF_search_파일_현재상영중인_영화조회_성공(){ + // given + LocalDateTime now = LocalDateTime.now(); + Genre genre = Genre.SF; + String search = "파일"; + + // when + List result = movieRepository.searchWithFiltering(now, genre, search); + + // then + assertThat(result).isNotEmpty(); + assertThat(result).allMatch(movie -> movie.getGenre().equals(Genre.SF) && movie.getMovieName().contains("파일")); + } + + @Test + @DisplayName("장르와 search가 둘 다 null인 경우 현재 상영중인 영화를 성공적으로 조회한다.") + void 장르_search_null_현재상영중인_영화조회_성공(){ + // given + LocalDateTime now = LocalDateTime.now(); + + // when + List result = movieRepository.searchWithFiltering(now, null, null); + + // then + assertThat(result).isNotEmpty(); + } +} \ No newline at end of file diff --git a/infra/src/test/resources/application.yml b/infra/src/test/resources/application.yml new file mode 100644 index 000000000..7967e2b81 --- /dev/null +++ b/infra/src/test/resources/application.yml @@ -0,0 +1,33 @@ +spring: + profiles: + active: test + +--- + +spring: + datasource: + url: jdbc:h2:mem:db;MODE=MYSQL + username: sa + password: + driver-class-name: org.h2.Driver + h2: + console: + enabled: true + path: /h2-console + jpa: + defer-datasource-initialization: true + database-platform: org.hibernate.dialect.H2Dialect + hibernate: + ddl-auto: create-drop + properties: + hibernate: + format_sql: true + generate-ddl: true + sql: + init: + data-locations: classpath:data.sql + mode: always + +logging: + level: + org.hibernate.SQL: debug \ No newline at end of file diff --git a/infra/src/test/resources/data.sql b/infra/src/test/resources/data.sql new file mode 100644 index 000000000..9f22fe4e7 --- /dev/null +++ b/infra/src/test/resources/data.sql @@ -0,0 +1,58 @@ +-- Theater Data +INSERT INTO theater (id, name, create_at, modify_at) +VALUES + (1, '상영관 1관', CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), + (2, '상영관 2관', CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), + (3, '상영관 3관', CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), + (4, '상영관 4관', CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), + (5, '상영관 5관', CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), + (6, '상영관 6관', CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), + (7, '상영관 7관', CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), + (8, '상영관 8관', CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), + (9, '상영관 9관', CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), + (10, '상영관 10관', CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()); + +-- Movie Data +INSERT INTO movie (id, name, thumbnail, genre, grade, release_date, running_time, create_at, modify_at) +VALUES + (1, '범죄도시', NULL, 'ACTION', 'FROM_15_AGE', DATEADD('DAY', -30, CURRENT_DATE()), 120, CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), --30일 전 개봉 + (2, '파일럿', NULL, 'SF', 'FROM_12_AGE', DATEADD('DAY', -15, CURRENT_DATE()), 135, CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), --15일 전 개봉 + (3, '기생충', NULL, 'ROMANCE', 'FROM_15_AGE', DATEADD('DAY', -10, CURRENT_DATE()), 132, CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), --10일 전 개봉 + (4, '인셉션', NULL, 'SF', 'FROM_15_AGE', DATEADD('DAY', -100, CURRENT_DATE()), 148, CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), --100일 전 개봉 + (5, '어벤져스: 엔드게임', NULL, 'ACTION', 'FROM_12_AGE', DATEADD('DAY', 100, CURRENT_DATE()), 181, CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()); --100일 후 개봉 + +-- Screening Data +-- 범죄도시 상영 스케줄 (종료) +INSERT INTO screening (id, movie_id, theater_id, start_at, end_at, create_at, modify_at) +VALUES + (1, 1, 1, TIMESTAMPADD(HOUR, 12, DATEADD('DAY', -30, CURRENT_DATE())), TIMESTAMPADD(HOUR, 14, DATEADD('DAY', -30, CURRENT_DATE())), CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), + (2, 1, 2, TIMESTAMPADD(HOUR, 14, DATEADD('DAY', -30, CURRENT_DATE())), TIMESTAMPADD(HOUR, 16, DATEADD('DAY', -30, CURRENT_DATE())), CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), + (3, 1, 3, TIMESTAMPADD(HOUR, 15, DATEADD('DAY', -30, CURRENT_DATE())), TIMESTAMPADD(HOUR, 17, DATEADD('DAY', -30, CURRENT_DATE())), CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), + (4, 1, 4, TIMESTAMPADD(HOUR, 17, DATEADD('DAY', -30, CURRENT_DATE())), TIMESTAMPADD(HOUR, 19, DATEADD('DAY', -30, CURRENT_DATE())), CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), + (5, 1, 5, TIMESTAMPADD(HOUR, 36, DATEADD('DAY', -30, CURRENT_DATE())), TIMESTAMPADD(HOUR, 38, DATEADD('DAY', -30, CURRENT_DATE())), CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()); + +-- 파일럿 상영 스케줄 (진행) +INSERT INTO screening (id, movie_id, theater_id, start_at, end_at, create_at, modify_at) +VALUES + (6, 2, 2, TIMESTAMPADD(HOUR, -12, CURRENT_TIMESTAMP()), TIMESTAMPADD(HOUR, -10, CURRENT_TIMESTAMP()), CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), + (7, 2, 3, TIMESTAMPADD(HOUR, 14, CURRENT_TIMESTAMP()), TIMESTAMPADD(HOUR, 16, CURRENT_TIMESTAMP()), CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), + (8, 2, 4, TIMESTAMPADD(HOUR, 15, CURRENT_TIMESTAMP()), TIMESTAMPADD(HOUR, 17, CURRENT_TIMESTAMP()), CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), + (9, 2, 5, TIMESTAMPADD(HOUR, 17, CURRENT_TIMESTAMP()), TIMESTAMPADD(HOUR, 19, CURRENT_TIMESTAMP()), CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), + (10, 2, 6, TIMESTAMPADD(HOUR, 36, CURRENT_TIMESTAMP()), TIMESTAMPADD(HOUR, 38, CURRENT_TIMESTAMP()), CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()); + +-- 기생충 상영 스케줄 (진행) +INSERT INTO screening (id, movie_id, theater_id, start_at, end_at, create_at, modify_at) +VALUES + (11, 3, 3, TIMESTAMPADD(HOUR, -10, CURRENT_TIMESTAMP()), TIMESTAMPADD(HOUR, -8, CURRENT_TIMESTAMP()), CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), + (12, 3, 4, TIMESTAMPADD(HOUR, 13, CURRENT_TIMESTAMP()), TIMESTAMPADD(HOUR, 15, CURRENT_TIMESTAMP()), CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), + (13, 3, 5, TIMESTAMPADD(HOUR, 14, CURRENT_TIMESTAMP()), TIMESTAMPADD(HOUR, 16, CURRENT_TIMESTAMP()), CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), + (14, 3, 6, TIMESTAMPADD(HOUR, 18, CURRENT_TIMESTAMP()), TIMESTAMPADD(HOUR, 20, CURRENT_TIMESTAMP()), CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), + (15, 3, 7, TIMESTAMPADD(HOUR, 20, CURRENT_TIMESTAMP()), TIMESTAMPADD(HOUR, 22, CURRENT_TIMESTAMP()), CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()); + +-- 인셉션 상영 스케줄 (종료) +INSERT INTO screening (id, movie_id, theater_id, start_at, end_at, create_at, modify_at) +VALUES + (16, 4, 4, TIMESTAMPADD(HOUR, 10, DATEADD('DAY', -100, CURRENT_DATE())), TIMESTAMPADD(HOUR, 12, DATEADD('DAY', -100, CURRENT_DATE())), CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), + (17, 4, 5, TIMESTAMPADD(HOUR, 13, DATEADD('DAY', -100, CURRENT_DATE())), TIMESTAMPADD(HOUR, 15, DATEADD('DAY', -100, CURRENT_DATE())), CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()), + (18, 4, 6, TIMESTAMPADD(HOUR, 14, DATEADD('DAY', -100, CURRENT_DATE())), TIMESTAMPADD(HOUR, 16, DATEADD('DAY', -100, CURRENT_DATE())), CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()); + diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 000000000..f81f247de --- /dev/null +++ b/settings.gradle @@ -0,0 +1,5 @@ +rootProject.name = 'multi-modules' +include 'web' +include 'domain' +include 'infra' + diff --git a/web/build.gradle b/web/build.gradle new file mode 100644 index 000000000..333b1a600 --- /dev/null +++ b/web/build.gradle @@ -0,0 +1,10 @@ +bootJar.enabled = true + +jar.enabled = false + +dependencies { + implementation project(':domain') + implementation project(':infra') + + implementation "org.springframework.boot:spring-boot-starter-web" +} \ No newline at end of file diff --git a/web/http/movie.http b/web/http/movie.http new file mode 100644 index 000000000..596667909 --- /dev/null +++ b/web/http/movie.http @@ -0,0 +1,7 @@ +### 1. 상영중인 영화 조회 +GET localhost:8080/v1/movies?nowShowing=TRUE +Content-Type: application/json + +### 2. 전체 영화 조회 +GET localhost:8080/v1/movies?nowShowing=FALSE&genre=ROMANCE&search=3 +Content-Type: application/json \ No newline at end of file diff --git a/web/src/main/java/com/example/Hang99Application.java b/web/src/main/java/com/example/Hang99Application.java new file mode 100644 index 000000000..302040aa5 --- /dev/null +++ b/web/src/main/java/com/example/Hang99Application.java @@ -0,0 +1,21 @@ +package com.example; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.data.domain.AuditorAware; + +import java.util.Optional; + +@SpringBootApplication +public class Hang99Application { + + public static void main(String[] args) { + SpringApplication.run(Hang99Application.class, args); + } + + @Bean + public AuditorAware auditorProvider(){ + return () -> Optional.of("SYSTEM"); + } +} \ No newline at end of file diff --git a/web/src/main/java/com/example/exception/BaseException.java b/web/src/main/java/com/example/exception/BaseException.java new file mode 100644 index 000000000..c339c15d9 --- /dev/null +++ b/web/src/main/java/com/example/exception/BaseException.java @@ -0,0 +1,20 @@ +package com.example.exception; + +import com.example.response.status.ResponseStatus; +import lombok.Getter; + +@Getter +public class BaseException extends RuntimeException{ + private final ResponseStatus exceptionStatus; + + + public BaseException(ResponseStatus exceptionStatus) { + super(exceptionStatus.getMessage()); + this.exceptionStatus = exceptionStatus; + } + + public BaseException(String exceptionMessage, ResponseStatus exceptionStatus) { + super(exceptionMessage); + this.exceptionStatus = exceptionStatus; + } +} diff --git a/web/src/main/java/com/example/exception/BaseExceptionHandler.java b/web/src/main/java/com/example/exception/BaseExceptionHandler.java new file mode 100644 index 000000000..e9652425f --- /dev/null +++ b/web/src/main/java/com/example/exception/BaseExceptionHandler.java @@ -0,0 +1,68 @@ +package com.example.exception; + +import com.example.response.BaseErrorResponse; +import com.example.response.code.BaseCode; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.TypeMismatchException; +import org.springframework.http.HttpStatus; +import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.MissingServletRequestParameterException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.servlet.NoHandlerFoundException; + +import java.io.IOException; + +@Slf4j +@RestControllerAdvice +public class BaseExceptionHandler { + @ResponseStatus(HttpStatus.BAD_REQUEST) + @ExceptionHandler({BaseException.class,NoHandlerFoundException.class, TypeMismatchException.class}) + public BaseErrorResponse handle_BadRequest(Exception exception) { + log.info("[BaseExceptionControllerAdvice: handle_BadRequest 호출]", exception); + return new BaseErrorResponse(BaseCode.URL_NOT_FOUND); + } + + @ResponseStatus(HttpStatus.BAD_REQUEST) + @ExceptionHandler(HttpRequestMethodNotSupportedException.class) + public BaseErrorResponse handle_HttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) { + log.info("[BaseExceptionControllerAdvice: handle_HttpRequestMethodNotSupportedException 호출]", e); + return new BaseErrorResponse(BaseCode.METHOD_NOT_ALLOWED); + } + + @ResponseStatus(HttpStatus.BAD_REQUEST) + @ExceptionHandler(IllegalArgumentException.class) + public BaseErrorResponse handle_IllegalArgumentException(IllegalArgumentException e) { + log.info("[BaseExceptionControllerAdvice: handle_IllegalArgumentException 호출]", e); + return new BaseErrorResponse(BaseCode.BAD_REQUEST, e.getMessage()); + } + + @ResponseStatus(HttpStatus.BAD_REQUEST) + @ExceptionHandler(IllegalStateException.class) + public BaseErrorResponse handle_IllegalStatusException(IllegalStateException e) { + log.info("[BaseExceptionControllerAdvice: handle_IllegalStatusException 호출]", e); + return new BaseErrorResponse(BaseCode.BAD_REQUEST, e.getMessage()); + } + + @ResponseStatus(HttpStatus.BAD_REQUEST) + @ExceptionHandler(IOException.class) + public BaseErrorResponse handle_IOException(IOException e) { + log.info("[BaseExceptionControllerAdvice: handle_IOException 호출]", e); + return new BaseErrorResponse(BaseCode.BAD_REQUEST, e.getMessage()); + } + + @ResponseStatus(HttpStatus.BAD_REQUEST) + @ExceptionHandler(MissingServletRequestParameterException.class) + public BaseErrorResponse handleMissingServletRequestParameterException(MissingServletRequestParameterException e) { + log.info("[GlobalExceptionHandler] MissingServletRequestParameterException", e); + return new BaseErrorResponse(BaseCode.NO_REQUEST_PARAMETER); + } + + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + @ExceptionHandler(RuntimeException.class) + public BaseErrorResponse handle_RuntimeException(Exception e) { + log.error("[BaseExceptionControllerAdvice: handle_RuntimeException 호출]", e); + return new BaseErrorResponse(BaseCode.SERVER_ERROR); + } +} diff --git a/web/src/main/java/com/example/movie/controller/MovieController.java b/web/src/main/java/com/example/movie/controller/MovieController.java new file mode 100644 index 000000000..1596640fa --- /dev/null +++ b/web/src/main/java/com/example/movie/controller/MovieController.java @@ -0,0 +1,31 @@ +package com.example.movie.controller; + +import com.example.movie.dto.MoviesDetailResponse; +import com.example.movie.service.MovieService; +import com.example.jpa.entity.movie.Genre; +import com.example.response.BaseResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.time.LocalDateTime; +import java.util.List; + +@RestController +@RequiredArgsConstructor +public class MovieController { + + private final MovieService movieService; + + @GetMapping("/v1/movies") + public BaseResponse> getMoviesNowShowing( + @RequestParam(value = "nowShowing") Boolean isNowShowing, + @RequestParam(value = "genre", required = false)Genre genre, + @RequestParam(value = "search", required = false)String search + ) { + List response = movieService.getMovies(LocalDateTime.now(), isNowShowing, genre, search); + return new BaseResponse<>(response); + } + +} diff --git a/web/src/main/java/com/example/reservation/controller/ReservationController.java b/web/src/main/java/com/example/reservation/controller/ReservationController.java new file mode 100644 index 000000000..11fd8714d --- /dev/null +++ b/web/src/main/java/com/example/reservation/controller/ReservationController.java @@ -0,0 +1,22 @@ +package com.example.reservation.controller; + +import com.example.reservation.dto.ReservationRequest; +import com.example.reservation.service.ReservationService; +import com.example.response.BaseResponse; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequiredArgsConstructor +public class ReservationController { + private final ReservationService reservationService; + + @PostMapping("/v1/reservation") + public BaseResponse getMoviesNowShowing(@RequestBody @Valid ReservationRequest reservationRequest) throws InterruptedException { + reservationService.reserveSeat(reservationRequest); + return new BaseResponse<>(); + } +} diff --git a/web/src/main/java/com/example/response/BaseErrorResponse.java b/web/src/main/java/com/example/response/BaseErrorResponse.java new file mode 100644 index 000000000..1c584e38a --- /dev/null +++ b/web/src/main/java/com/example/response/BaseErrorResponse.java @@ -0,0 +1,56 @@ +package com.example.response; + +import com.example.response.status.ResponseStatus; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import lombok.Getter; + +import java.time.LocalDateTime; + +@Getter +@JsonPropertyOrder({"code","status","message","timestamp"}) +public class BaseErrorResponse implements ResponseStatus { + private final int code; + private final int status; + private final String message; + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss") + private final LocalDateTime timestamp; + + public BaseErrorResponse(ResponseStatus status) { + this.code = status.getCode(); + this.status = status.getStatus(); + this.message = status.getMessage(); + this.timestamp = LocalDateTime.now(); + } + + public BaseErrorResponse(ResponseStatus status, String message) { + this.code = status.getCode(); + this.status = status.getStatus(); + this.message = message; + this.timestamp = LocalDateTime.now(); + } + + @Override + public int getCode() { + return code; + } + + @Override + public int getStatus() { + return status; + } + + @Override + public String getMessage() { + return message; + } + + public String convertToJson() throws JsonProcessingException { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.registerModule(new JavaTimeModule()); + return objectMapper.writeValueAsString(this); + } +} diff --git a/web/src/main/java/com/example/response/BaseResponse.java b/web/src/main/java/com/example/response/BaseResponse.java new file mode 100644 index 000000000..5efaea3ce --- /dev/null +++ b/web/src/main/java/com/example/response/BaseResponse.java @@ -0,0 +1,48 @@ +package com.example.response; + +import com.example.response.status.ResponseStatus; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import lombok.Getter; + +import static com.example.response.code.BaseCode.SUCCESS; + + +@Getter +@JsonPropertyOrder({"code","status","message","result"}) +public class BaseResponse implements ResponseStatus { + private final int code; + private final int status; + private final String message; + + @JsonInclude(JsonInclude.Include.NON_NULL) + private final T result; + + + public BaseResponse() { + this.code = SUCCESS.getCode(); + this.status = SUCCESS.getStatus(); + this.message = SUCCESS.getMessage(); + this.result = null; + } + + public BaseResponse(T result) { + this.code = SUCCESS.getCode(); + this.status = SUCCESS.getStatus(); + this.message = SUCCESS.getMessage(); + this.result = result; + } + + public int getCode() { + return code; + } + + public int getStatus() { + return status; + } + + public String getMessage() { + return message; + } +} + diff --git a/web/src/main/java/com/example/response/code/BaseCode.java b/web/src/main/java/com/example/response/code/BaseCode.java new file mode 100644 index 000000000..f5fb7fcf1 --- /dev/null +++ b/web/src/main/java/com/example/response/code/BaseCode.java @@ -0,0 +1,50 @@ +package com.example.response.code; + +import com.example.response.status.ResponseStatus; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; + +@RequiredArgsConstructor +public enum BaseCode implements ResponseStatus { + + /** + * 1000: 요청 성공 (OK) + */ + SUCCESS(1000,HttpStatus.OK.value(), "요청에 성공하였습니다."), + + /** + * 2000: Request 오류 (BAD_REQUEST) + */ + BAD_REQUEST(2000, HttpStatus.BAD_REQUEST.value(), "유효하지 않은 요청입니다."), + URL_NOT_FOUND(2001, HttpStatus.BAD_REQUEST.value(), "유효하지 않은 URL 입니다."), + METHOD_NOT_ALLOWED(2002, HttpStatus.METHOD_NOT_ALLOWED.value(), "해당 URL에서는 지원하지 않는 HTTP Method 입니다."), + NO_REQUEST_PARAMETER(2005,HttpStatus.BAD_REQUEST.value(),"요청 파라미터는 필수로 입력해야합니다."), + + + /** + * 3000: Server, Database 오류 (INTERNAL_SERVER_ERROR) + */ + SERVER_ERROR(3000, HttpStatus.INTERNAL_SERVER_ERROR.value(), "서버에서 오류가 발생하였습니다."), + DATABASE_ERROR(3001, HttpStatus.INTERNAL_SERVER_ERROR.value(), "데이터베이스에서 오류가 발생하였습니다."), + BAD_SQL_GRAMMAR(3002, HttpStatus.INTERNAL_SERVER_ERROR.value(), "SQL에 오류가 있습니다."); + + private final int code; + private final int status; + private final String message; + + + @Override + public int getCode() { + return code; + } + + @Override + public int getStatus() { + return status; + } + + @Override + public String getMessage() { + return message; + } +} diff --git a/web/src/main/java/com/example/response/status/ResponseStatus.java b/web/src/main/java/com/example/response/status/ResponseStatus.java new file mode 100644 index 000000000..5762a4956 --- /dev/null +++ b/web/src/main/java/com/example/response/status/ResponseStatus.java @@ -0,0 +1,7 @@ +package com.example.response.status; + +public interface ResponseStatus { + int getCode(); + int getStatus(); + String getMessage(); +} \ No newline at end of file diff --git a/web/src/test/java/com/example/Hang99ApplicationTest.java b/web/src/test/java/com/example/Hang99ApplicationTest.java new file mode 100644 index 000000000..0f6dfd7bd --- /dev/null +++ b/web/src/test/java/com/example/Hang99ApplicationTest.java @@ -0,0 +1,14 @@ +package com.example; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class Hang99ApplicationTest { + + @Test + void contextLoads(){ + + } + +} \ No newline at end of file diff --git a/web/src/test/java/com/example/movie/controller/MovieControllerTest.java b/web/src/test/java/com/example/movie/controller/MovieControllerTest.java new file mode 100644 index 000000000..1d78a8a26 --- /dev/null +++ b/web/src/test/java/com/example/movie/controller/MovieControllerTest.java @@ -0,0 +1,32 @@ +package com.example.movie.controller; + +import com.example.movie.service.MovieService; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@WebMvcTest(controllers = MovieController.class) +class MovieControllerTest { + + @Autowired + private MockMvc mockMvc; + @MockitoBean + private MovieService movieService; + + @Test + @DisplayName("장르 필터링 시 Enum 값이 아니면 예외가 발생한다.") + void 장르필터링_예외() throws Exception { + mockMvc.perform(get("/v1/movies") + .param("genre","weirdInput") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()); + } + +} \ No newline at end of file