Skip to content

Commit f9b3016

Browse files
committed
fix: SSE 수정
- 하트비트 수정
1 parent 112c774 commit f9b3016

File tree

2 files changed

+31
-18
lines changed

2 files changed

+31
-18
lines changed

src/main/java/org/dfbf/soundlink/domain/alert/service/AlertService.java

Lines changed: 22 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import org.dfbf.soundlink.global.exception.ResponseResult;
1010
import org.springframework.data.redis.core.RedisTemplate;
1111
import org.springframework.http.MediaType;
12+
import org.springframework.scheduling.annotation.Async;
1213
import org.springframework.stereotype.Service;
1314
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
1415

@@ -62,8 +63,24 @@ private void sendPendingAlerts(Long userId, SseEmitter sseEmitter) {
6263
});
6364
}
6465

66+
@Async
67+
public void sendPing(Long userId) throws InterruptedException {
68+
while (alertRepository.getEmitterId(userId).isPresent()) {
69+
String emitterId = alertRepository.getEmitterId(userId).get();
70+
SseEmitter sseEmitter = alertRepository.get(emitterId).get();
71+
72+
Thread.sleep(40000); // 40초마다 빈 메시지 전송
73+
try {
74+
sseEmitter.send(SseEmitter.event().name("ping").data("connection keep-alive"));
75+
} catch (IOException e) {
76+
log.error("Ping 전송 중 오류 발생", e);
77+
break; // 오류가 발생하면 while 루프 종료
78+
}
79+
}
80+
}
81+
6582
// SSE 서버 연결
66-
public SseEmitter connectAlarm(Long id, String lastEventId) {
83+
public SseEmitter connectAlarm(Long id, String lastEventId) throws InterruptedException {
6784

6885
if (lastEventId != null && !lastEventId.isEmpty()) {
6986
log.info("[lastEventId] {}", lastEventId);
@@ -86,26 +103,13 @@ public SseEmitter connectAlarm(Long id, String lastEventId) {
86103
}); // 타임아웃 시 처리
87104

88105
try {
89-
log.info("아아 알림 테스트 {}", emitterId);
90-
sseEmitter.send(SseEmitter.event()
91-
.id(this.createEmitterId(id))
92-
.name("open")
93-
.data("connect completed!!")
94-
);
95-
} catch (IOException e) {
106+
// ping 이벤트를 비동기적으로 전송
107+
sendPing(id);
108+
} catch (InterruptedException e) {
96109
log.error("Error sending ping", e);
110+
throw new RuntimeException(e);
97111
}
98112

99-
// 사용자에게 전송되지 않은 알림 전송
100-
this.sendPendingAlerts(id, sseEmitter);
101-
102-
Executors.newSingleThreadExecutor().submit(() -> {
103-
while (true) {
104-
Thread.sleep(40000); // 45초마다 빈 메시지를 전송
105-
sseEmitter.send(SseEmitter.event().name("ping").data("connection keep-alive"));
106-
}
107-
});
108-
109113
return sseEmitter;
110114
}
111115

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package org.dfbf.soundlink.global.config;
2+
3+
import org.springframework.context.annotation.Configuration;
4+
import org.springframework.scheduling.annotation.EnableAsync;
5+
6+
@Configuration
7+
@EnableAsync
8+
public class AsyncConfig {
9+
}

0 commit comments

Comments
 (0)