|
| 1 | +package cmf.commitField.domain.user.service; |
| 2 | + |
| 3 | +import cmf.commitField.domain.user.entity.MatchSession; |
| 4 | +import lombok.RequiredArgsConstructor; |
| 5 | +import org.springframework.data.redis.core.RedisTemplate; |
| 6 | +import org.springframework.messaging.simp.SimpMessagingTemplate; |
| 7 | +import org.springframework.stereotype.Service; |
| 8 | + |
| 9 | +import java.util.List; |
| 10 | +import java.util.UUID; |
| 11 | + |
| 12 | +@Service |
| 13 | +@RequiredArgsConstructor |
| 14 | +public class MatchService { |
| 15 | + private final String MATCH_QUEUE_KEY = "commit_match_queue"; |
| 16 | + private final RedisTemplate<String, String> redisTemplate; |
| 17 | + private final SimpMessagingTemplate messagingTemplate; |
| 18 | + |
| 19 | + public void enqueueUser(String userId, int matchDuration) { |
| 20 | + redisTemplate.opsForList().rightPush(MATCH_QUEUE_KEY, userId + ":" + matchDuration); |
| 21 | + checkAndMatch(); |
| 22 | + } |
| 23 | + |
| 24 | + private void checkAndMatch() { |
| 25 | + List<String> queue = redisTemplate.opsForList().range(MATCH_QUEUE_KEY, 0, -1); |
| 26 | + if (queue != null && queue.size() >= 2) { |
| 27 | + String player1 = queue.get(0); |
| 28 | + String player2 = queue.get(1); |
| 29 | + |
| 30 | + // ๋ ์ ์ ๋ฅผ ๋งค์นญ ํ ์ ๊ฑฐ |
| 31 | + redisTemplate.opsForList().leftPop(MATCH_QUEUE_KEY); |
| 32 | + redisTemplate.opsForList().leftPop(MATCH_QUEUE_KEY); |
| 33 | + |
| 34 | + startMatch(player1, player2); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + private void startMatch(String player1, String player2) { |
| 39 | + String matchId = UUID.randomUUID().toString(); |
| 40 | + int matchDuration = Integer.parseInt(player1.split(":")[1]); // ๊ฒฝ์ ์๊ฐ ๊ฐ์ ธ์ค๊ธฐ |
| 41 | + |
| 42 | + MatchSession matchSession = new MatchSession(matchId, player1, player2, matchDuration); |
| 43 | + redisTemplate.opsForHash().put("active_matches", matchId, matchSession); |
| 44 | + |
| 45 | + messagingTemplate.convertAndSend("/topic/match", "๋งค์นญ ์๋ฃ: " + player1 + " vs " + player2); |
| 46 | + } |
| 47 | +} |
0 commit comments