|
| 1 | +package com.backend.domain.bid.service; |
| 2 | + |
| 3 | +import com.backend.domain.bid.dto.BidMessageDto; |
| 4 | +import com.backend.domain.bid.dto.BidResponseDto; |
| 5 | +import com.backend.domain.bid.entity.Bid; |
| 6 | +import com.backend.domain.bid.enums.BidStatus; |
| 7 | +import com.backend.domain.bid.repository.BidRepository; |
| 8 | +import com.backend.domain.member.entity.Member; |
| 9 | +import com.backend.domain.member.repository.MemberRepository; |
| 10 | +import com.backend.domain.notification.service.BidNotificationService; |
| 11 | +import com.backend.domain.product.entity.Product; |
| 12 | +import com.backend.domain.product.enums.AuctionStatus; |
| 13 | +import com.backend.domain.product.event.helper.ProductChangeTracker; |
| 14 | +import com.backend.domain.product.repository.jpa.ProductRepository; |
| 15 | +import com.backend.global.exception.ServiceException; |
| 16 | +import com.backend.global.lock.DistributedLock; |
| 17 | +import com.backend.global.websocket.service.WebSocketService; |
| 18 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 19 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 20 | +import lombok.RequiredArgsConstructor; |
| 21 | +import lombok.extern.slf4j.Slf4j; |
| 22 | +import org.springframework.context.ApplicationEventPublisher; |
| 23 | +import org.springframework.data.redis.core.RedisTemplate; |
| 24 | +import org.springframework.scheduling.annotation.Scheduled; |
| 25 | +import org.springframework.stereotype.Service; |
| 26 | +import org.springframework.transaction.annotation.Transactional; |
| 27 | + |
| 28 | +import java.time.LocalDateTime; |
| 29 | +import java.util.List; |
| 30 | + |
| 31 | +@Slf4j |
| 32 | +@Service |
| 33 | +@RequiredArgsConstructor |
| 34 | +public class BidConsumerService { |
| 35 | + |
| 36 | + private final RedisTemplate<String, String> redisTemplate; |
| 37 | + private final ObjectMapper objectMapper; |
| 38 | + private final ProductRepository productRepository; |
| 39 | + private final MemberRepository memberRepository; |
| 40 | + private final BidRepository bidRepository; |
| 41 | + private final WebSocketService webSocketService; |
| 42 | + private final BidNotificationService bidNotificationService; |
| 43 | + private final ApplicationEventPublisher eventPublisher; |
| 44 | + |
| 45 | + @Scheduled(fixedDelay = 100) // 0.1초마다 실행 |
| 46 | + public void consumeBidQueue() { |
| 47 | + String messageJson = redisTemplate.opsForList().leftPop("bid_queue"); |
| 48 | + |
| 49 | + if (messageJson != null) { |
| 50 | + try { |
| 51 | + BidMessageDto messageDto = objectMapper.readValue(messageJson, BidMessageDto.class); |
| 52 | + processBid(messageDto); |
| 53 | + } catch (JsonProcessingException e) { |
| 54 | + log.error("입찰 메시지 역직렬화 실패: {}", messageJson, e); |
| 55 | + } catch (Exception e) { |
| 56 | + log.error("입찰 처리 중 예외 발생: {}", e.getMessage(), e); |
| 57 | + // 예외 발생 시, 해당 메시지를 별도의 Dead Letter Queue로 보내거나 로깅 후 폐기하는 정책 필요 |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + @DistributedLock(key = "'product:' + #messageDto.productId", waitTime = 10, leaseTime = 10) |
| 63 | + public void processBid(BidMessageDto messageDto) { |
| 64 | + Long productId = messageDto.getProductId(); |
| 65 | + Long bidderId = messageDto.getBidderId(); |
| 66 | + Long price = messageDto.getPrice(); |
| 67 | + |
| 68 | + // Product/Member 조회 |
| 69 | + Product product = productRepository.findByIdWithBids(productId) |
| 70 | + .orElseThrow(() -> ServiceException.notFound("존재하지 않는 상품입니다.")); |
| 71 | + Member member = memberRepository.findById(bidderId) |
| 72 | + .orElseThrow(() -> ServiceException.notFound("존재하지 않는 사용자입니다.")); |
| 73 | + |
| 74 | + // 유효성 검증 |
| 75 | + validateBid(product, member, price); |
| 76 | + |
| 77 | + Long previousHighestPrice = bidRepository.findHighestBidPrice(productId).orElse(null); |
| 78 | + |
| 79 | + // 이전 최고 입찰자 확인 (입찰 밀림 알림용) |
| 80 | + Bid previousHighestBid = null; |
| 81 | + if (previousHighestPrice != null) { |
| 82 | + List<Bid> recentBids = bidRepository.findNBids(productId, 10); |
| 83 | + previousHighestBid = recentBids.stream() |
| 84 | + .filter(bid -> bid.getBidPrice().equals(previousHighestPrice)) |
| 85 | + .findFirst() |
| 86 | + .orElse(null); |
| 87 | + } |
| 88 | + |
| 89 | + // 입찰 생성 및 저장 |
| 90 | + Bid savedBid = saveBid(product, member, price); |
| 91 | + |
| 92 | + // 상품 업데이트 |
| 93 | + updateProduct(product, savedBid, price); |
| 94 | + |
| 95 | + // 응답 생성 |
| 96 | + BidResponseDto bidResponse = createBidResponse(savedBid); |
| 97 | + |
| 98 | + // 실시간 브로드캐스트 |
| 99 | + webSocketService.broadcastBidUpdate(productId, bidResponse); |
| 100 | + |
| 101 | + // 입찰 성공 알림 (현재 입찰자에게) |
| 102 | + bidNotificationService.notifyBidSuccess(bidderId, product, price); |
| 103 | + |
| 104 | + // 입찰 밀림 알림 (이전 최고 입찰자에게) |
| 105 | + if (previousHighestBid != null && !previousHighestBid.getMember().getId().equals(bidderId)) { |
| 106 | + bidNotificationService.notifyBidOutbid( |
| 107 | + previousHighestBid.getMember().getId(), |
| 108 | + product, |
| 109 | + previousHighestBid.getBidPrice(), |
| 110 | + price |
| 111 | + ); |
| 112 | + } |
| 113 | + log.info("입찰 성공: 상품 ID {}, 입찰자 ID {}, 입찰가 {}", productId, bidderId, price); |
| 114 | + } |
| 115 | + |
| 116 | + private Bid saveBid(Product product, Member member, Long bidPrice) { |
| 117 | + Bid bid = Bid.builder() |
| 118 | + .bidPrice(bidPrice) |
| 119 | + .status(BidStatus.BIDDING) |
| 120 | + .product(product) |
| 121 | + .member(member) |
| 122 | + .build(); |
| 123 | + return bidRepository.save(bid); |
| 124 | + } |
| 125 | + |
| 126 | + private void validateBid(Product product, Member member, Long bidPrice) { |
| 127 | + // 경매 상태 확인 |
| 128 | + validateAuctionStatus(product); |
| 129 | + |
| 130 | + // 경매 시간 확인 |
| 131 | + validateAuctionTime(product); |
| 132 | + |
| 133 | + // 본인 상품 입찰 방지 |
| 134 | + validateNotSelfBid(product, member); |
| 135 | + |
| 136 | + // 입찰 금액 유효성 검증 |
| 137 | + validateBidPrice(bidPrice, product); |
| 138 | + } |
| 139 | + |
| 140 | + private void validateAuctionStatus(Product product) { |
| 141 | + if (!AuctionStatus.BIDDING.getDisplayName().equals(product.getStatus())) { |
| 142 | + throw ServiceException.badRequest("현재 입찰할 수 없는 상품입니다."); |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + private void validateAuctionTime(Product product) { |
| 147 | + LocalDateTime now = LocalDateTime.now(); |
| 148 | + if (product.getStartTime() != null && now.isBefore(product.getStartTime())) { |
| 149 | + throw ServiceException.badRequest("경매가 아직 시작되지 않았습니다."); |
| 150 | + } |
| 151 | + if (product.getEndTime() != null && now.isAfter(product.getEndTime())) { |
| 152 | + throw ServiceException.badRequest("경매가 이미 종료되었습니다."); |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + private void validateNotSelfBid(Product product, Member member) { |
| 157 | + Member seller = product.getSeller(); |
| 158 | + if (seller != null && seller.getId().equals(member.getId())) { |
| 159 | + throw ServiceException.badRequest("본인이 등록한 상품에는 입찰할 수 없습니다."); |
| 160 | + } |
| 161 | + } |
| 162 | + |
| 163 | + private void validateBidPrice(Long bidPrice, Product product) { |
| 164 | + // 입찰 금액 기본 검증 |
| 165 | + if (bidPrice == null || bidPrice <= 0) { |
| 166 | + throw ServiceException.badRequest("입찰 금액은 0보다 커야 합니다."); |
| 167 | + } |
| 168 | + |
| 169 | + // 현재 최고가보다 높은지 확인 |
| 170 | + Long currentHighestPrice = bidRepository.findHighestBidPrice(product.getId()).orElse(product.getInitialPrice()); |
| 171 | + if (bidPrice <= currentHighestPrice) { |
| 172 | + throw ServiceException.badRequest("입찰 금액이 현재 최고가인 " + currentHighestPrice + "원 보다 높아야 합니다."); |
| 173 | + } |
| 174 | + |
| 175 | + // 최소 입찰단위 100원 |
| 176 | + if (bidPrice % 100 != 0) { |
| 177 | + throw ServiceException.badRequest("입찰 금액은 100원 단위로 입력해주세요."); |
| 178 | + } |
| 179 | + } |
| 180 | + |
| 181 | + private void updateProduct(Product product, Bid savedBid, Long newPrice) { |
| 182 | + ProductChangeTracker tracker = ProductChangeTracker.of(product); |
| 183 | + |
| 184 | + product.addBid(savedBid); |
| 185 | + product.setCurrentPrice(newPrice); |
| 186 | + |
| 187 | + productRepository.save(product); // 변경사항을 명시적으로 저장 |
| 188 | + |
| 189 | + tracker.publishChanges(eventPublisher, product); |
| 190 | + } |
| 191 | + |
| 192 | + private BidResponseDto createBidResponse(Bid bid) { |
| 193 | + return new BidResponseDto( |
| 194 | + bid.getId(), |
| 195 | + bid.getProduct().getId(), |
| 196 | + bid.getMember().getId(), |
| 197 | + bid.getBidPrice(), |
| 198 | + bid.getStatus(), |
| 199 | + bid.getCreateDate() |
| 200 | + ); |
| 201 | + } |
| 202 | +} |
0 commit comments