Skip to content

Commit 54c86d7

Browse files
authored
[fix] : 웹소켓 클라이언트 구독 경로 수정, principal 기반 자동 라우팅 -> 직접 경로로 전송 (#262)
* [fix] : 웹소켓 클라이언트 구독 경로 수정, principal 기반 자동 라우팅 -> 직접 경로로 전송 * [fix] : 테스트코드 수정 * [fix] : 불필요 로그 제거
1 parent eeac0bb commit 54c86d7

3 files changed

Lines changed: 30 additions & 51 deletions

File tree

backend/src/main/java/com/back/api/notification/listener/NotificationEventListener.java

Lines changed: 11 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -47,20 +47,11 @@ public void handleNotificationMessage(NotificationMessage message) {
4747
.build();
4848

4949
notificationRepository.save(notification);
50-
log.info("알림 생성 완료 - userId: {}, type: {}, from: {}",
51-
message.getUserId(),
52-
message.getNotificationType(),
53-
message.getDomainName());
5450

5551
// 웹소켓으로 실시간 알림 전송
5652
sendNotificationViaWebSocket(message.getUserId(), notification);
5753

5854
} catch (Exception e) {
59-
log.error("알림 생성 실패 - userId: {}, type: {}",
60-
message.getUserId(),
61-
message.getNotificationType(),
62-
e);
63-
// 알림 생성 실패가 원본 트랜잭션에 영향 주지 않음
6455
}
6556
}
6657

@@ -71,29 +62,26 @@ public void handleNotificationMessage(NotificationMessage message) {
7162
* @param notification 전송할 알림 엔티티
7263
*/
7364
private void sendNotificationViaWebSocket(Long userId, Notification notification) {
74-
// 사용자 온라인 여부 확인
75-
if (!sessionManager.isUserOnline(userId)) {
76-
log.debug("사용자 오프라인 - 웹소켓 전송 생략 - userId: {}", userId);
65+
66+
boolean isOnline = sessionManager.isUserOnline(userId);
67+
68+
if (!isOnline) {
69+
//log.debug("사용자 오프라인 - 웹소켓 전송 생략 - userId: {}", userId);
7770
return;
7871
}
7972

8073
try {
81-
// DTO 변환
8274
NotificationResponseDto dto = NotificationResponseDto.from(notification);
8375

84-
// 웹소켓 전송
85-
messagingTemplate.convertAndSendToUser(
86-
userId.toString(),
87-
"/notifications",
88-
dto
89-
);
76+
// convertAndSendToUser 대신 직접 경로로 전송
77+
String directDestination = "/user/" + userId + "/notifications";
78+
79+
messagingTemplate.convertAndSend(directDestination, dto);
9080

91-
log.info("웹소켓 전송 성공 - userId: {}, notificationId: {}", userId, notification.getId());
81+
//log.info("=== 웹소켓 전송 성공 - userId: {}, notificationId: {}", userId, notification.getId());
9282

9383
} catch (Exception e) {
94-
log.warn("웹소켓 전송 실패 - userId: {}, notificationId: {}, error: {}",
95-
userId, notification.getId(), e.getMessage());
96-
// 전송 실패해도 DB에는 저장되어 있으므로 예외를 던지지 않음
84+
//log.error("=== 웹소켓 전송 실패 - userId: {}, error: {}", userId, e.getMessage(), e);
9785
}
9886
}
9987
}

backend/src/main/java/com/back/global/config/WebSocketConfig.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
2424
public void configureMessageBroker(MessageBrokerRegistry registry) {
2525

2626
//클라이언트 구독 경로
27-
registry.enableSimpleBroker("/topic/", "/queue/");
27+
registry.enableSimpleBroker("/topic/", "/queue/", "/user");
2828

2929
//클라이언트 발행 경로
3030
registry.setApplicationDestinationPrefixes("/app");

backend/src/test/java/com/back/api/notification/listener/NotificationEventListenerTest.java

Lines changed: 18 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -144,9 +144,8 @@ void publishOrdersSuccessMessage_UserOnline_SavesAndSendsWebSocket() {
144144
assertThat(saved.isRead()).isFalse();
145145

146146
// 웹소켓 전송 확인
147-
verify(messagingTemplate).convertAndSendToUser(
148-
eq(testUser.getId().toString()),
149-
eq("/notifications"),
147+
verify(messagingTemplate).convertAndSend(
148+
eq("/user/" + testUser.getId() + "/notifications"),
150149
any(NotificationResponseDto.class)
151150
);
152151
});
@@ -177,10 +176,9 @@ void publishOrdersSuccessMessage_UserOffline_SavesOnlyWithoutWebSocket() {
177176
assertThat(notifications).hasSize(1);
178177

179178
// 웹소켓 미전송 확인
180-
verify(messagingTemplate, never()).convertAndSendToUser(
179+
verify(messagingTemplate, never()).convertAndSend(
181180
anyString(),
182-
anyString(),
183-
any()
181+
any(Object.class)
184182
);
185183
});
186184
}
@@ -247,9 +245,8 @@ void publishOrderFailedMessage_UserOnline_SavesAndSendsWebSocket() {
247245
assertThat(saved.getTitle()).isEqualTo("주문 및 결제 실패");
248246
assertThat(saved.getMessage()).contains("테스트 이벤트", "154000원", "실패");
249247

250-
verify(messagingTemplate).convertAndSendToUser(
251-
eq(testUser.getId().toString()),
252-
eq("/notifications"),
248+
verify(messagingTemplate).convertAndSend(
249+
eq("/user/" + testUser.getId() + "/notifications"),
253250
any(NotificationResponseDto.class)
254251
);
255252
});
@@ -315,9 +312,8 @@ void publishPreRegisterDoneMessage_UserOnline_SavesAndSendsWebSocket() {
315312
assertThat(saved.getTitle()).isEqualTo("사전등록 완료");
316313
assertThat(saved.getMessage()).contains("테스트 이벤트", "사전등록이 완료");
317314

318-
verify(messagingTemplate).convertAndSendToUser(
319-
eq(testUser.getId().toString()),
320-
eq("/notifications"),
315+
verify(messagingTemplate).convertAndSend(
316+
eq("/user/" + testUser.getId() + "/notifications"),
321317
any(NotificationResponseDto.class)
322318
);
323319
});
@@ -382,9 +378,8 @@ void publishQueueEntriesMessage_UserOnline_SavesAndSendsWebSocket() {
382378
assertThat(saved.getTitle()).isEqualTo("티켓팅 시작");
383379
assertThat(saved.getMessage()).contains("테스트 이벤트", "입장 준비가 완료");
384380

385-
verify(messagingTemplate).convertAndSendToUser(
386-
eq(testUser.getId().toString()),
387-
eq("/notifications"),
381+
verify(messagingTemplate).convertAndSend(
382+
eq("/user/" + testUser.getId() + "/notifications"),
388383
any(NotificationResponseDto.class)
389384
);
390385
});
@@ -448,10 +443,9 @@ void publishMessage_NonExistentUser_DoesNotSaveNotification() {
448443
assertThat(notifications).isEmpty();
449444

450445
// 웹소켓도 전송되지 않음
451-
verify(messagingTemplate, never()).convertAndSendToUser(
452-
anyString(),
446+
verify(messagingTemplate, never()).convertAndSend(
453447
anyString(),
454-
any()
448+
any(Object.class)
455449
);
456450
});
457451
}
@@ -462,10 +456,9 @@ void publishMessage_WebSocketFails_StillSavesNotification() {
462456
// given
463457
given(sessionManager.isUserOnline(testUser.getId())).willReturn(true);
464458
willThrow(new RuntimeException("웹소켓 전송 실패"))
465-
.given(messagingTemplate).convertAndSendToUser(
466-
anyString(),
459+
.given(messagingTemplate).convertAndSend(
467460
anyString(),
468-
any()
461+
any(Object.class)
469462
);
470463

471464
// when
@@ -486,9 +479,8 @@ void publishMessage_WebSocketFails_StillSavesNotification() {
486479
assertThat(notifications).hasSize(1);
487480

488481
// 웹소켓 전송 시도는 있었음
489-
verify(messagingTemplate).convertAndSendToUser(
490-
eq(testUser.getId().toString()),
491-
eq("/notifications"),
482+
verify(messagingTemplate).convertAndSend(
483+
eq("/user/" + testUser.getId() + "/notifications"),
492484
any(NotificationResponseDto.class)
493485
);
494486
});
@@ -529,9 +521,8 @@ void publishMultipleMessages_AllProcessedSuccessfully() {
529521
);
530522

531523
// 웹소켓 4번 전송 확인
532-
verify(messagingTemplate, times(4)).convertAndSendToUser(
533-
eq(testUser.getId().toString()),
534-
eq("/notifications"),
524+
verify(messagingTemplate, times(4)).convertAndSend(
525+
eq("/user/" + testUser.getId() + "/notifications"),
535526
any(NotificationResponseDto.class)
536527
);
537528
});

0 commit comments

Comments
 (0)