99import org .dfbf .soundlink .global .exception .ResponseResult ;
1010import org .springframework .data .redis .core .RedisTemplate ;
1111import org .springframework .http .MediaType ;
12+ import org .springframework .scheduling .annotation .Async ;
1213import org .springframework .stereotype .Service ;
1314import 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
0 commit comments