Skip to content

Commit

Permalink
상속을 활용하여 Inventory Redis Key 구조를 수정에도 유연한 구조로 리팩터링
Browse files Browse the repository at this point in the history
  • Loading branch information
daadaadaah committed Jul 6, 2023
1 parent 4894245 commit 5504c2c
Show file tree
Hide file tree
Showing 6 changed files with 68 additions and 46 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -107,22 +107,24 @@ public List<Object> execute(RedisOperations operations) throws DataAccessExcepti

int PAGE_NUMBER = 0;

String dealProductUuid = UUID.randomUUID().toString();
UUID dealProductUuid = UUID.randomUUID();

String dealProductUuidString = dealProductUuid.toString();

int expirationInSeconds = 86_400; // TODO : 일단 임시로 24시간으로 설정, 유효시간을 설정해서 관리할 것인가? 아니면 따로 lambda나 batch 서버를 두어서 삭제시킬 것인가?

saveDealProductUuids(
DealType.TIME_DEAL+":"+dealOpenDate+":"+PAGE_NUMBER,
dealProductUuid,
dealProductUuidString,
scoreForSortSet,
expirationInSeconds
);

saveDealProductEntity(
"timeDealProducts:"+dealOpenDate,
dealProductUuid,
dealProductUuidString,
TimeDealProductEntity.builder()
.dealProductUuid(UUID.fromString(dealProductUuid))
.dealProductUuid(dealProductUuid)
.dealProductTile("1000원 할인 상품 "+scoreForSortSet)
.productMainImgThumbnailUrl("/main_thumbnail_test.png")
.productOriginPrice(1000*(scoreForSortSet+1))
Expand All @@ -137,8 +139,7 @@ public List<Object> execute(RedisOperations operations) throws DataAccessExcepti
expirationInSeconds
);

saveInventory(
"timeDealProductInventory:"+dealProductUuid,
saveInventory(dealProductUuid,
10 // TODO : 일단 통일 시킴
);

Expand All @@ -165,8 +166,8 @@ private void saveDealProductEntity(String redisKey, String hashKey, TimeDealProd
);
}

private void saveInventory(String redisKey, int redisValue) {
inventoryCommandRepository.set(redisKey, redisValue);
private void saveInventory(UUID dealProductUuid, int redisValue) {
inventoryCommandRepository.set(dealProductUuid, redisValue);
}

private static int getRandomNumber(int min, int max) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
Expand Down Expand Up @@ -120,26 +119,11 @@ private Map<String, Integer> createTimeDealProductInventoryMap(Set<String> timeD
* getTimeDealProductInventories 는 Redis에서 딜상품의 재고량을 가져오는 함수이다.
*/
private List<Integer> getTimeDealProductInventories(Set<String> timeDealProductUuidSets) {
Set<String> timeDealProductInventoryKeySets = createTimeDealProductInventoryKeys(timeDealProductUuidSets);

List<Integer> integers = inventoryQueryRepository.getMany(timeDealProductInventoryKeySets);
List<Integer> integers = inventoryQueryRepository.getMany(timeDealProductUuidSets);

return integers;
}

/**
* createTimeDealProductInventoryKeys 는 Redis에서 딜상품의 재고량을 가져오기 위한 key들의 목록을 만드는 함수이다.
*/
private Set<String> createTimeDealProductInventoryKeys(Set<String> timeDealProductUuids) {
Set<String> timeDealProductInventoryKeys = new HashSet<>();

for(String timeDealProductUuid: timeDealProductUuids) {
timeDealProductInventoryKeys.add("timeDealProductInventory:"+timeDealProductUuid);
}

return timeDealProductInventoryKeys;
}

/**
* createDealProductSummaries 는 DealProductSummary 목록을 만드는 함수이다.
*/
Expand Down Expand Up @@ -205,9 +189,7 @@ private TimeDealProductEntity getTimeDealProductEntity(UUID dealProductUuid) {
* getTimeDealProductInventory 는 Redis에서 TimeDealProductInventory 을 가져오는 함수이다.
*/
private int getTimeDealProductInventory(UUID timeDealProductUuid) {
String redisKey = "timeDealProductInventory:"+timeDealProductUuid.toString();

return inventoryQueryRepository.get(redisKey);
return inventoryQueryRepository.get(timeDealProductUuid);
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package com.hcommerce.heecommerce.inventory;

import com.hcommerce.heecommerce.common.dao.RedisStringsRepository;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class InventoryCommandRepository {
public class InventoryCommandRepository extends InventoryRepository {


private final RedisStringsRepository redisStringsRepository;

Expand All @@ -16,19 +18,27 @@ public InventoryCommandRepository(
this.redisStringsRepository = redisStringsRepository;
}

public void set(String key, int amount) {
public void set(UUID dealProductUuid, int amount) {
String key = super.getRedisKey(dealProductUuid);

redisStringsRepository.set(key, String.valueOf(amount));
}

public void delete(String key) {
public void delete(UUID dealProductUuid) {
String key = super.getRedisKey(dealProductUuid);

redisStringsRepository.delete(key);
}

public int decreaseByAmount(String key, int amount) {
public int decreaseByAmount(UUID dealProductUuid, int amount) {
String key = super.getRedisKey(dealProductUuid);

return (int) redisStringsRepository.decreaseByAmount(key, Long.valueOf(amount));
}

public void increaseByAmount(String key, int amount) {
public void increaseByAmount(UUID dealProductUuid, int amount) {
String key = super.getRedisKey(dealProductUuid);

redisStringsRepository.increaseByAmount(key, Long.valueOf(amount));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@

import com.hcommerce.heecommerce.common.dao.RedisStringsRepository;
import com.hcommerce.heecommerce.common.utils.TypeConversionUtils;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class InventoryQueryRepository {
public class InventoryQueryRepository extends InventoryRepository {

private final RedisStringsRepository redisStringsRepository;

Expand All @@ -17,13 +20,31 @@ public InventoryQueryRepository(RedisStringsRepository redisStringsRepository) {
this.redisStringsRepository = redisStringsRepository;
}

public int get(String key) {
public int get(UUID dealProductUuid) {
String key = super.getRedisKey(dealProductUuid);

return Integer.valueOf(redisStringsRepository.get(key));
}

public List<Integer> getMany(Set<String> keys) {
public List<Integer> getMany(Set<String> uuidStrings) {
Set<String> keys = createRedisKeys(uuidStrings);

List<String> inventories = redisStringsRepository.getMany(keys);

return TypeConversionUtils.convertStringsToIntegers(inventories);
}

private Set<String> createRedisKeys(Set<String> uuidStrings) {
Set<String> redisKeys = new HashSet<>();

Iterator<String> iterator = uuidStrings.iterator();

while (iterator.hasNext()) {
String uuid = iterator.next();

redisKeys.add(super.getRedisKey(UUID.fromString(uuid)));
}

return redisKeys;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.hcommerce.heecommerce.inventory;

import java.util.UUID;

public class InventoryRepository {

private final static String INVENTORY_REDIS_KEY_PREFIX = "timeDealProductInventory:";

protected String getRedisKey(UUID dealProductUuid) {
return INVENTORY_REDIS_KEY_PREFIX + dealProductUuid;
}
}
16 changes: 6 additions & 10 deletions src/main/java/com/hcommerce/heecommerce/order/OrderService.java
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,9 @@ public void placeOrder(OrderForm orderForm) {
// 1. 유효성 검사

// 2. 재고량 감소
String key = "dealProductInventory:"+dealProductUuid.toString();

int orderQuantity = orderForm.getOrderQuantity();

int inventoryAfterDecrease = inventoryCommandRepository.decreaseByAmount(key, orderQuantity);
int inventoryAfterDecrease = inventoryCommandRepository.decreaseByAmount(dealProductUuid, orderQuantity);

// 3. 실제 주문량 계산
int realOrderQuantity = calculateRealOrderQuantity(inventoryAfterDecrease, orderQuantity, orderForm.getOutOfStockHandlingOption());
Expand All @@ -74,7 +72,7 @@ public void placeOrder(OrderForm orderForm) {
boolean isSuccessPayment = false; // TODO : 임시 데이터

if(!isSuccessPayment) {
rollbackReducedInventory(key, realOrderQuantity);
rollbackReducedInventory(dealProductUuid, realOrderQuantity);
return;
}

Expand Down Expand Up @@ -135,11 +133,11 @@ private void saveOrder() {
/**
* rollbackReducedInventory 는 임의로 감소시킨 재고량을 다시 원상복귀하기 위한 함수이다.
* 함수로 만든 이유는 다양한 원인으로 재고량을 rollback 시켜줘야 하므로, 함수로 만들어 재활용하고 싶었기 때문이다.
* @param key : 원상복귀해야 하는 딜 상품 key
* @param dealProductUuid : 원상복귀해야 하는 딜 상품 key
* @param amount : 원상복귀해야 하는 재고량
*/
private void rollbackReducedInventory(String key, int amount) {
inventoryCommandRepository.increaseByAmount(key, amount);
private void rollbackReducedInventory(UUID dealProductUuid, int amount) {
inventoryCommandRepository.increaseByAmount(dealProductUuid, amount);
}

/**
Expand Down Expand Up @@ -184,9 +182,7 @@ private void validateHasDealProductUuid(UUID dealProductUuid) {
* checkOrderQuantityInInventory 는 주문 가능한 수량을 체크하는 함수이다.
*/
private int checkOrderQuantityInInventory(UUID dealProductUuid, int orderQuantity, OutOfStockHandlingOption outOfStockHandlingOption) {
String redisKey = "timeDealProductInventory:"+dealProductUuid.toString();

int inventory = inventoryQueryRepository.get(redisKey);
int inventory = inventoryQueryRepository.get(dealProductUuid);

if(orderQuantity > inventory && outOfStockHandlingOption == OutOfStockHandlingOption.ALL_CANCEL) {
throw new OrderOverStockException();
Expand Down

0 comments on commit 5504c2c

Please sign in to comment.