Skip to content

Commit

Permalink
Merge pull request #1648 from innovationacademy-kr/be/dev/refactor-re…
Browse files Browse the repository at this point in the history
…dis-to-db#1647

[BE] REFACTOR: 유저 현재 보유 재화를 REDIS -> RDBMS 이전 #1647
  • Loading branch information
enaenen authored Jun 25, 2024
2 parents ee21200 + 2da3d45 commit ef700a6
Show file tree
Hide file tree
Showing 8 changed files with 40 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
import org.ftclub.cabinet.item.service.ItemQueryService;
import org.ftclub.cabinet.item.service.ItemRedisService;
import org.ftclub.cabinet.mapper.ItemMapper;
import org.ftclub.cabinet.utils.lock.LockUtil;
import org.ftclub.cabinet.user.service.UserCommandService;
import org.ftclub.cabinet.user.service.UserQueryService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
Expand All @@ -35,6 +36,8 @@ public class AdminItemFacadeService {
private final ItemMapper itemMapper;

private final ItemRedisService itemRedisService;
private final UserCommandService userCommandService;
private final UserQueryService userQueryService;

@Transactional
public void createItem(Integer Price, Sku sku, ItemType type) {
Expand All @@ -44,16 +47,18 @@ public void createItem(Integer Price, Sku sku, ItemType type) {
@Transactional
public void assignItem(List<Long> userIds, Sku sku) {
Item item = itemQueryService.getBySku(sku);
Long price = item.getPrice();
LocalDateTime now = null;
if (item.getPrice() > 0) {
if (price > 0) {
now = LocalDateTime.now();
userIds.forEach(userId -> LockUtil.lockRedisCoin(userId, () -> {
long coinAmount = itemRedisService.getCoinAmount(userId);
userIds.forEach(userId -> {
long coinAmount = userQueryService.getUser(userId).getCoin();
itemRedisService.saveCoinCount(userId, coinAmount + item.getPrice());

long totalCoinSupply = itemRedisService.getTotalCoinSupply();
itemRedisService.saveTotalCoinSupply(totalCoinSupply + item.getPrice());
}));
userCommandService.updateCoinAmount(userId, price);
});
}
itemHistoryCommandService.createItemHistories(userIds, item.getId(), now);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ public void endUserLent(List<Long> userIds) {
LocalDateTime now = LocalDateTime.now();
List<LentHistory> lentHistories =
lentQueryService.findUserActiveLentHistoriesInCabinetForUpdate(userIds.get(0));
System.out.println("lentHistories = " + lentHistories);
if (lentHistories.isEmpty()) {
Long cabinetId = lentRedisService.findCabinetJoinedUser(userIds.get(0));
if (cabinetId != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
import org.ftclub.cabinet.log.Logging;
import org.ftclub.cabinet.mapper.ItemMapper;
import org.ftclub.cabinet.user.domain.User;
import org.ftclub.cabinet.user.service.UserCommandService;
import org.ftclub.cabinet.user.service.UserQueryService;
import org.ftclub.cabinet.utils.lock.LockUtil;
import org.springframework.context.ApplicationEventPublisher;
Expand All @@ -67,6 +68,7 @@ public class ItemFacadeService {
private final ItemMapper itemMapper;
private final ItemPolicyService itemPolicyService;
private final ApplicationEventPublisher eventPublisher;
private final UserCommandService userCommandService;


/**
Expand Down Expand Up @@ -207,15 +209,16 @@ public CoinCollectionRewardResponseDto collectCoinAndIssueReward(Long userId) {

// Redis에 코인 변화량 저장
saveCoinChangeOnRedis(userId, reward);
userCommandService.updateCoinAmount(userId, (long) reward);

return new CoinCollectionRewardResponseDto(reward);
}

private void saveCoinChangeOnRedis(Long userId, final int reward) {
LockUtil.lockRedisCoin(userId, () -> {
// Redis에 유저 리워드 저장
long coins = itemRedisService.getCoinAmount(userId);
itemRedisService.saveCoinCount(userId, coins + reward);
// long coins = itemRedisService.getCoinAmount(userId);
// itemRedisService.saveCoinCount(userId, coins + reward);

// Redis에 전체 코인 발행량 저장
long totalCoinSupply = itemRedisService.getTotalCoinSupply();
Expand Down Expand Up @@ -294,7 +297,11 @@ public void purchaseItem(Long userId, Sku sku) {

Item item = itemQueryService.getBySku(sku);
long price = item.getPrice();
long userCoin = itemRedisService.getCoinAmount(userId);

// 유저의 보유 재화량
// long userCoin = itemRedisService.getCoinAmount(userId);
long userCoin = user.getCoin();


// 아이템 Policy 검증
itemPolicyService.verifyOnSale(price);
Expand All @@ -311,6 +318,7 @@ public void purchaseItem(Long userId, Sku sku) {
long totalCoinUsage = itemRedisService.getTotalCoinUsage();
itemRedisService.saveTotalCoinUsage(totalCoinUsage + price);
});
userCommandService.updateCoinAmount(userId, price);
}

@Transactional
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,6 @@ public class ItemRedisService {
private final ItemRedis itemRedis;
private final ItemHistoryRepository itemHistoryRepository;

public long getCoinAmount(Long userId) {
String userIdString = userId.toString();
String coinAmount = itemRedis.getCoinAmount(userIdString);
if (coinAmount == null) {
long coin = itemHistoryRepository.findAllByUserId(userId).stream()
.mapToLong(ih -> ih.getItem().getPrice())
.reduce(Long::sum).orElse(0L);
itemRedis.saveCoinAmount(userIdString, Long.toString(coin));
return coin;
}
return Integer.parseInt(coinAmount);
}

public void saveCoinCount(Long userId, long coinCount) {
itemRedis.saveCoinAmount(userId.toString(), String.valueOf(coinCount));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,15 @@ public class User {
@Column(name = "PUSH_ALARM", columnDefinition = "boolean default false")
private boolean pushAlarm;

@NotNull
@Column(name = "COIN", columnDefinition = "bigint default 0")
private Long coin;

protected User(String name, String email, LocalDateTime blackholedAt) {
this.name = name;
this.email = email;
this.blackholedAt = blackholedAt;
this.coin = 0L;
// this.role = userRole;
setDefaultAlarmStatus();
}
Expand Down Expand Up @@ -143,4 +147,8 @@ public void changeAlarmStatus(UpdateAlarmRequestDto updateAlarmRequestDto) {
public boolean isBlackholed() {
return blackholedAt != null && blackholedAt.isBefore(LocalDateTime.now());
}

public void addCoin(Long reward) {
this.coin += reward;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
import org.ftclub.cabinet.log.Logging;
import org.ftclub.cabinet.occupiedtime.OccupiedTimeManager;
import org.ftclub.cabinet.user.domain.User;
import org.ftclub.cabinet.utils.lock.LockUtil;
import org.springframework.stereotype.Service;

@Service
Expand Down Expand Up @@ -43,10 +42,10 @@ public void issueLentExtension() {

List<User> users = userQueryService.findAllUsersByNames(userNames);
Item coinRewardItem = itemQueryService.getBySku(Sku.COIN_FULL_TIME);

users.forEach(user -> {
Long userId = user.getId();
LockUtil.lockRedisCoin(userId, () ->
saveCoinChangeOnRedis(userId, coinRewardItem.getPrice()));
user.addCoin(coinRewardItem.getPrice());
itemHistoryCommandService.createItemHistory(userId, coinRewardItem.getId());
});
}
Expand All @@ -59,8 +58,8 @@ public void issueLentExtension() {
*/
private void saveCoinChangeOnRedis(Long userId, long price) {
// 유저 재화 변동량 Redis에 저장
long userCoinCount = itemRedisService.getCoinAmount(userId);
itemRedisService.saveCoinCount(userId, userCoinCount + price);
// long userCoinCount = itemRedisService.getCoinAmount(userId);
// itemRedisService.saveCoinCount(userId, userCoinCount + price);

// 전체 재화 변동량 Redis에 저장
long totalCoinSupply = itemRedisService.getTotalCoinSupply();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,4 +109,10 @@ public void updateUserBlackholedAtById(Long userId, LocalDateTime blackholedAt)
user.changeBlackholedAt(blackholedAt);
userRepository.save(user);
}

public void updateCoinAmount(Long userId, Long reward) {
User user = userRepository.findById(userId)
.orElseThrow(ExceptionStatus.NOT_FOUND_USER::asServiceException);
user.addCoin(reward);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public MyProfileResponseDto getProfile(UserSessionDto user) {
AlarmTypeResponseDto userAlarmTypes = currentUser.getAlarmTypes();
boolean isDeviceTokenExpired = userAlarmTypes.isPush()
&& fcmTokenRedisService.findByUserName(user.getName()).isEmpty();
Long coins = itemRedisService.getCoinAmount(userId);
Long coins = currentUser.getCoin();
return userMapper.toMyProfileResponseDto(user, cabinet, banHistory,
lentExtensionResponseDto, userAlarmTypes, isDeviceTokenExpired, coins);
}
Expand Down

0 comments on commit ef700a6

Please sign in to comment.