|
| 1 | +package com.axon.entry_service.service.redisListener; |
| 2 | + |
| 3 | +import lombok.extern.slf4j.Slf4j; |
| 4 | +import org.springframework.data.redis.connection.Message; |
| 5 | +import org.springframework.data.redis.core.StringRedisTemplate; |
| 6 | +import org.springframework.data.redis.listener.KeyExpirationEventMessageListener; |
| 7 | +import org.springframework.data.redis.listener.RedisMessageListenerContainer; |
| 8 | +import org.springframework.stereotype.Component; |
| 9 | + |
| 10 | +import java.nio.charset.StandardCharsets; |
| 11 | +import java.time.Duration; |
| 12 | +import java.util.Base64; |
| 13 | + |
| 14 | +@Slf4j |
| 15 | +@Component |
| 16 | +public class ReservationExpirationListener extends KeyExpirationEventMessageListener { |
| 17 | + private final StringRedisTemplate redisTemplate; |
| 18 | + |
| 19 | + public ReservationExpirationListener(RedisMessageListenerContainer listener, StringRedisTemplate redisTemplate) { |
| 20 | + super(listener); |
| 21 | + this.redisTemplate = redisTemplate; |
| 22 | + } |
| 23 | + |
| 24 | + @Override |
| 25 | + public void onMessage(Message message, byte[] pattern) { |
| 26 | + String expiredKey = message.toString(); // 1차 토큰 전체 문장 |
| 27 | + |
| 28 | + // 1차 토큰 만료인지 확인 |
| 29 | + if(!expiredKey.startsWith("RESERVATION_TOKEN:")) {return;} |
| 30 | + |
| 31 | + try { |
| 32 | + String tokenValue = expiredKey.replace("RESERVATION_TOKEN:", ""); |
| 33 | + String decoded = new String(Base64.getDecoder().decode(tokenValue), StandardCharsets.UTF_8); |
| 34 | + |
| 35 | + String[] parts = decoded.split(":"); |
| 36 | + if(parts.length < 2) { |
| 37 | + log.warn("Invalid token format ignored: {}", decoded); |
| 38 | + return; |
| 39 | + } |
| 40 | + |
| 41 | + String userId = parts[0]; |
| 42 | + String campaignActivityId = parts[1]; |
| 43 | + |
| 44 | + // 각 파드간 중복 실행 방지용 |
| 45 | + String lockKey = "processed:restore:" + tokenValue; |
| 46 | + Boolean isWinner = redisTemplate.opsForValue() |
| 47 | + .setIfAbsent(lockKey, "1", Duration.ofMinutes(1)); |
| 48 | + |
| 49 | + if(Boolean.TRUE.equals(isWinner)) { |
| 50 | + String counterKey = "campaign:" + campaignActivityId + ":counter"; |
| 51 | + Long remaining = redisTemplate.opsForValue().decrement(counterKey); |
| 52 | + |
| 53 | + String usersKey = "campaign:" + campaignActivityId + ":users"; |
| 54 | + redisTemplate.opsForSet().remove(usersKey, userId); |
| 55 | + |
| 56 | + log.info("♻️ Stock Restored! Activity: {}, User: {}, Remaining: {}", campaignActivityId, userId, remaining); |
| 57 | + } else { |
| 58 | + log.debug("Another pod Accessed and Skipped decrease request"); |
| 59 | + } |
| 60 | + } catch (Exception e) { |
| 61 | + log.error("1차 토큰 만료로 인한 재고 복구 실패 token={}", expiredKey, e); |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments