-
Notifications
You must be signed in to change notification settings - Fork 3
[release] BE #1069
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
[release] BE #1069
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
59a9099
chore: redis 의존성 추가
lepitaaar 0a5420f
feat: redis pub/sub 구조를 위한 모델 정의
lepitaaar 5e8d4ee
refactor: sperate semester to year and semesterTerm
lepitaaar 65f8d62
refactor: fixing compiler error
lepitaaar 76e4eef
feature: year 검증 추가
lepitaaar 2d48099
feat: 분산락을 위한 레디스 도입
lepitaaar 1be72af
feat: redis 리스너 추가
lepitaaar 12a0e49
feat: 지원자 상태 공유를 위한 SSE 서비스 구현
lepitaaar 434f05f
refactor: SSE 이벤트 처리 로직 개선 및 기존 구현 제거
lepitaaar cd02d82
fix: serializer LocalDateTime 파싱 가능하게 추가
lepitaaar 37f69bf
fix: TIMEOUT 길이 증가 및 잘못된 redis 채널 구독 형식
lepitaaar 8072b54
Merge pull request #1046 from Moadong/refactor/#1045-seperate-awards-…
seongwon030 55536a6
feat: redis publishing try-catch 추가
lepitaaar 9d9bb74
Merge pull request #1061 from Moadong/refactor/#1007-share-applicants…
lepitaaar File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
188 changes: 38 additions & 150 deletions
188
backend/src/main/java/moadong/club/service/ClubApplyAdminService.java
Large diffs are not rendered by default.
Oops, something went wrong.
42 changes: 42 additions & 0 deletions
42
backend/src/main/java/moadong/global/config/RedisConfig.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| package moadong.global.config; | ||
|
|
||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.data.redis.connection.RedisConnectionFactory; | ||
| import org.springframework.data.redis.core.RedisTemplate; | ||
| import org.springframework.data.redis.listener.RedisMessageListenerContainer; | ||
| import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; | ||
| import org.springframework.data.redis.serializer.StringRedisSerializer; | ||
|
|
||
| @Configuration | ||
| public class RedisConfig { | ||
|
|
||
| @Bean | ||
| public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) { | ||
| RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); | ||
| redisTemplate.setConnectionFactory(connectionFactory); | ||
|
|
||
| ObjectMapper objectMapper = new ObjectMapper(); | ||
| objectMapper.registerModule(new JavaTimeModule()); | ||
|
|
||
| GenericJackson2JsonRedisSerializer jsonSerializer = new GenericJackson2JsonRedisSerializer(objectMapper); | ||
|
|
||
| redisTemplate.setKeySerializer(new StringRedisSerializer()); | ||
| redisTemplate.setValueSerializer(jsonSerializer); | ||
|
|
||
| redisTemplate.setHashKeySerializer(new StringRedisSerializer()); | ||
| redisTemplate.setHashValueSerializer(jsonSerializer); | ||
|
|
||
| return redisTemplate; | ||
| } | ||
|
|
||
| @Bean | ||
| public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory) { | ||
| RedisMessageListenerContainer container = new RedisMessageListenerContainer(); | ||
| container.setConnectionFactory(connectionFactory); | ||
| return container; | ||
| } | ||
| } | ||
|
|
11 changes: 11 additions & 0 deletions
11
backend/src/main/java/moadong/sse/dto/ApplicantSseDto.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| package moadong.sse.dto; | ||
|
|
||
| import lombok.Data; | ||
| import moadong.sse.enums.ApplicantEventType; | ||
|
|
||
| @Data | ||
| public class ApplicantSseDto { | ||
| private String clubId; | ||
| private ApplicantEventType event; | ||
| private Object data; | ||
| } |
6 changes: 6 additions & 0 deletions
6
backend/src/main/java/moadong/sse/enums/ApplicantEventType.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| package moadong.sse.enums; | ||
|
|
||
| public enum ApplicantEventType { | ||
| APPLICANT_STATUS_UPDATE, | ||
| ADDED_NEW_APPLICANT, | ||
| } |
167 changes: 167 additions & 0 deletions
167
backend/src/main/java/moadong/sse/service/ApplicantsStatusShareSse.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,167 @@ | ||
| package moadong.sse.service; | ||
|
|
||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import jakarta.annotation.PostConstruct; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import moadong.club.payload.dto.ApplicantStatusEvent; | ||
| import moadong.club.repository.ClubApplicationFormsRepository; | ||
| import moadong.global.exception.ErrorCode; | ||
| import moadong.global.exception.RestApiException; | ||
| import moadong.user.payload.CustomUserDetails; | ||
| import org.springframework.data.redis.connection.Message; | ||
| import org.springframework.data.redis.connection.MessageListener; | ||
| import org.springframework.data.redis.core.RedisTemplate; | ||
| import org.springframework.data.redis.listener.PatternTopic; | ||
| import org.springframework.data.redis.listener.RedisMessageListenerContainer; | ||
| import org.springframework.scheduling.annotation.Scheduled; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; | ||
|
|
||
| import java.nio.charset.StandardCharsets; | ||
| import java.util.Map; | ||
| import java.util.UUID; | ||
| import java.util.concurrent.ConcurrentHashMap; | ||
|
|
||
| @Slf4j | ||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class ApplicantsStatusShareSse implements MessageListener { | ||
|
|
||
| private final ClubApplicationFormsRepository clubApplicationFormsRepository; | ||
| private final RedisTemplate<String, Object> redisTemplate; | ||
| private final RedisMessageListenerContainer redisMessageListenerContainer; | ||
| private final ObjectMapper objectMapper; | ||
|
|
||
| private final Map<String, Map<String, SseEmitter>> sseConnections = new ConcurrentHashMap<>(); | ||
|
|
||
| private static final long SSE_EMITTER_TIME_OUT = 60 * 60 * 1000L; | ||
| private static final int MAX_SESSIONS_PER_CLUB = 20; | ||
| private static final String CHANNEL_PREFIX = "sse:applicant-status:"; | ||
|
|
||
| @PostConstruct | ||
| public void init() { | ||
| redisMessageListenerContainer.addMessageListener(this, new PatternTopic(CHANNEL_PREFIX + "*")); | ||
| } | ||
|
|
||
| public SseEmitter createSseSession(String applicationFormId, CustomUserDetails user) { | ||
| String clubId = user.getClubId(); | ||
|
|
||
| clubApplicationFormsRepository.findByClubIdAndId(clubId, applicationFormId) | ||
| .orElseThrow(() -> new RestApiException(ErrorCode.APPLICATION_NOT_FOUND)); | ||
|
|
||
| String connectionKey = applicationFormId + "_" + UUID.randomUUID(); | ||
|
|
||
| Map<String, SseEmitter> clubEmitters = sseConnections.computeIfAbsent(clubId, k -> new ConcurrentHashMap<>()); | ||
|
|
||
| if (clubEmitters.size() >= MAX_SESSIONS_PER_CLUB) { | ||
| String keyToRemove = clubEmitters.keySet().iterator().next(); | ||
| SseEmitter oldEmitter = clubEmitters.get(keyToRemove); | ||
|
|
||
| if (oldEmitter != null) { | ||
| oldEmitter.complete(); | ||
| clubEmitters.remove(keyToRemove); | ||
| } | ||
| } | ||
lepitaaar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| SseEmitter emitter = new SseEmitter(SSE_EMITTER_TIME_OUT); | ||
| clubEmitters.put(connectionKey, emitter); | ||
|
|
||
| Runnable removeCallback = () -> { | ||
| sseConnections.computeIfPresent(clubId, (key, innerMap) -> { | ||
| innerMap.remove(connectionKey); | ||
| return innerMap.isEmpty() ? null : innerMap; | ||
| }); | ||
| }; | ||
|
|
||
| emitter.onCompletion(removeCallback); | ||
| emitter.onTimeout(removeCallback); | ||
| emitter.onError((ex) -> { | ||
| if (ex.getMessage() != null && ex.getMessage().contains("Broken pipe")) { | ||
| log.info("SSE Client Disconnected [Club: {}, Key: {}]", clubId, connectionKey); | ||
| } else { | ||
| log.error("SSE Error [Club: {}, Key: {}]", clubId, connectionKey, ex); | ||
| } | ||
| removeCallback.run(); | ||
| }); | ||
|
|
||
| try { | ||
| emitter.send(SseEmitter.event().name("connected").data("ok")); | ||
| } catch (Exception e) { | ||
| removeCallback.run(); | ||
| emitter.completeWithError(e); | ||
| } | ||
|
|
||
| return emitter; | ||
| } | ||
|
|
||
| public void publishStatusChangeEvent(String clubId, String applicationFormId, ApplicantStatusEvent event) { | ||
| String channel = CHANNEL_PREFIX + clubId + ":" + applicationFormId; | ||
| redisTemplate.convertAndSend(channel, event); | ||
| } | ||
|
|
||
| @Override | ||
| public void onMessage(Message message, byte[] pattern) { | ||
| try { | ||
| String channel = new String(message.getChannel(), StandardCharsets.UTF_8); | ||
|
|
||
| String channelSuffix = channel.substring(CHANNEL_PREFIX.length()); | ||
| String[] parts = channelSuffix.split(":", 2); | ||
| if (parts.length < 2) { | ||
| log.warn("Invalid channel format: {}", channel); | ||
| return; | ||
| } | ||
|
|
||
| String clubId = parts[0]; | ||
| String applicationFormId = parts[1]; | ||
|
|
||
| ApplicantStatusEvent event = objectMapper.readValue(message.getBody(), ApplicantStatusEvent.class); | ||
| broadcastToLocalConnections(clubId, applicationFormId, event); | ||
|
|
||
| } catch (Exception e) { | ||
| log.error("Failed to process Redis message: {}", e.getMessage(), e); | ||
| } | ||
| } | ||
|
|
||
| private void broadcastToLocalConnections(String clubId, String applicationFormId, ApplicantStatusEvent event) { | ||
| Map<String, SseEmitter> clubEmitters = sseConnections.get(clubId); | ||
| if (clubEmitters == null || clubEmitters.isEmpty()) { | ||
| return; | ||
| } | ||
|
|
||
| String connectionKeyPrefix = applicationFormId + "_"; | ||
|
|
||
| clubEmitters.entrySet().stream() | ||
| .filter(entry -> entry.getKey().startsWith(connectionKeyPrefix)) | ||
| .forEach(entry -> { | ||
| String key = entry.getKey(); | ||
| SseEmitter emitter = entry.getValue(); | ||
|
|
||
| try { | ||
| emitter.send(SseEmitter.event() | ||
| .name("applicant-status-changed") | ||
| .data(event)); | ||
| } catch (Exception e) { | ||
| log.warn("SSE 이벤트 발송 실패: {}", e.getMessage()); | ||
| clubEmitters.remove(key); | ||
| try { | ||
| emitter.completeWithError(e); | ||
| } catch (Exception ignore) { | ||
| } | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| @Scheduled(fixedRate = 45000L) | ||
| public void sendHeartBeat() { | ||
| sseConnections.values() | ||
| .stream().flatMap(innerMap -> innerMap.values().stream()) | ||
| .forEach(emitter -> { | ||
| try { | ||
| emitter.send(SseEmitter.event().name("ping").data("")); | ||
| } catch (Exception e) { | ||
| emitter.completeWithError(e); | ||
| } | ||
| }); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.