Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update: Updated production code and tests #41

Open
wants to merge 1 commit into
base: feature/add-aop-lockretries
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ dependencies {

// swagger 패키지
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.6.0'

// lombok 테스트에서도 사용
testCompileOnly 'org.projectlombok:lombok'
testAnnotationProcessor 'org.projectlombok:lombok'
}

tasks.named('test') {
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.f_lab.la_planete.repository;

import com.f_lab.la_planete.aspect.RetryOnLockFailure;
import com.f_lab.la_planete.domain.Food;
import jakarta.persistence.LockModeType;
import jakarta.persistence.QueryHint;
Expand All @@ -14,6 +15,7 @@

public interface FoodRepository extends JpaRepository<Food, Long> {

@RetryOnLockFailure
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("SELECT f FROM Food f WHERE f.id = :id")
@QueryHints({ @QueryHint(name = "jakarta.persistence.lock.timeout", value = FIVE_SECONDS) })
Expand Down
12 changes: 8 additions & 4 deletions src/main/java/com/f_lab/la_planete/service/OrderService.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import com.f_lab.la_planete.domain.Payment;
import com.f_lab.la_planete.dto.request.OrderCreateRequestDTO;
import com.f_lab.la_planete.dto.response.OrderCreateResponseDTO;
import com.f_lab.la_planete.facade.FoodRepositoryFacade;
import com.f_lab.la_planete.repository.FoodRepository;
import com.f_lab.la_planete.repository.OrderRepository;
import com.f_lab.la_planete.repository.PaymentRepository;
import lombok.RequiredArgsConstructor;
Expand All @@ -23,16 +23,16 @@
public class OrderService {

private final OrderRepository orderRepository;
private final FoodRepositoryFacade foodRepositoryFacade;
private final FoodRepository foodRepository;
private final PaymentRepository paymentRepository;

@Transactional
public OrderCreateResponseDTO createFoodOrder(OrderCreateRequestDTO request) {

// 음식을 조회 후 요청한 수 만큼 빼기
Food food = foodRepositoryFacade.findFoodWithLockAndRetry(request.getFoodId());
Food food = findFoodWithLock(request.getFoodId());
food.minusQuantity(request.getQuantity());
foodRepositoryFacade.save(food);
foodRepository.save(food);

// 주문 생성 후 총 금액 계산
Order order = request.toEntity(food);
Expand All @@ -51,5 +51,9 @@ public OrderCreateResponseDTO createFoodOrder(OrderCreateRequestDTO request) {

return new OrderCreateResponseDTO("CREATED");
}

public Food findFoodWithLock(Long foodId) {
return foodRepository.findFoodByFoodIdWithPessimisticLock(foodId);
}
}

Original file line number Diff line number Diff line change
@@ -1,27 +1,39 @@
package com.f_lab.la_planete.facade;
package com.f_lab.la_planete.aspect;

import com.f_lab.la_planete.domain.Food;
import com.f_lab.la_planete.repository.FoodRepository;
import jakarta.persistence.LockTimeoutException;
import jakarta.persistence.PessimisticLockException;
import lombok.RequiredArgsConstructor;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.bean.override.mockito.MockitoBean;


import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.*;

@SpringBootTest
class FoodRepositoryFacadeTest {
class LockRetryAspectTest {

@MockitoBean
private FoodRepository foodRepository;

@Autowired
private FoodService foodService;

@InjectMocks
FoodRepositoryFacade foodRepositoryFacade;
@Mock
FoodRepository foodRepository;
@TestConfiguration
static class LockRetryAspectTestConfig {
@Bean
public FoodService foodService(FoodRepository foodRepository) {
return new FoodService(foodRepository);
}
}

@Test
@DisplayName("락 없이 첫 시도에 성공")
Expand All @@ -31,8 +43,10 @@ void test_find_food_lock_and_retry_success() {
Food expectedFood = createFood(foodId);

// when
when(foodRepository.findFoodByFoodIdWithPessimisticLock(anyLong())).thenReturn(expectedFood);
Food foundFood = foodRepositoryFacade.findFoodWithLockAndRetry(foodId);
when(foodRepository.findFoodByFoodIdWithPessimisticLock(foodId))
.thenReturn(expectedFood);

Food foundFood = foodService.findFood(foodId);

// then
assertThat(foundFood.getId()).isEqualTo(foodId);
Expand All @@ -50,10 +64,11 @@ void test_find_food_lock_and_retry_fail_on_first_then_success() {
.thenThrow(new PessimisticLockException())
.thenReturn(expectedFood);

Food foundFood = foodRepositoryFacade.findFoodWithLockAndRetry(foodId);
Food foundFood = foodService.findFood(foodId);

// then
assertThat(foundFood.getId()).isEqualTo(foodId);
verify(foodRepository, times(2)).findFoodByFoodIdWithPessimisticLock(foodId);
}

@Test
Expand All @@ -68,15 +83,25 @@ void test_find_food_lock_and_retry_fail() {
.thenThrow(new LockTimeoutException())
.thenThrow(new LockTimeoutException());

assertThatThrownBy(() -> foodRepositoryFacade.findFoodWithLockAndRetry(foodId))
// then
assertThatThrownBy(() -> foodService.findFood(foodId))
.isInstanceOf(RuntimeException.class)
.hasMessage("현재 너무 많은 요청을 처리하고 있습니다. 다시 시도해주세요");
}


private Food createFood(Long foodId) {
return Food.builder()
.id(foodId)
.build();
}
}

@RequiredArgsConstructor
static class FoodService {
private final FoodRepository foodRepository;

@RetryOnLockFailure
public Food findFood(Long foodId) {
return foodRepository.findFoodByFoodIdWithPessimisticLock(foodId);
}
}
}
Loading