🤔 의문 사항
@SubscribeMapping 과 @MessageMapping 설정한 메서드에서 메세지 객체를 반환하면 자동으로 역직렬화 하여 STOMP 요청의 응답으로 보냄.
Redis Pub/Sub으로 구현할 때, 그냥 메세지 객체를 반환하면 메세지 브로커가 전혀 적용이 안되는데 왜 Redis Pub/Sub을 쓰는거지?
기존 인 메모리 SimpleBroker에서 Redis로 메세지를 저장하여 사용하다보니 Redis Pub/Sub을 사용하여도 특별히 좋은 점을 찾지 못해 💣 서버를 분리해 보려고 프로젝트를 분리하려고 했는데 그건 너무 깊게 생각한 것 같다고 하셔서 기각
이전 메세지 로딩을 구현한 메세지 전송에서 응답이 정상적으로 도착하지 않음.
@Service
@RequiredArgsConstructor
public class RedisPublisher {
private final RedisTemplate<String, Object> redisTemplate;
public void publish(ChannelTopic topic, MessageDto message) {
redisTemplate.convertAndSend(topic.getTopic(), message);
}
public void publish(ChannelTopic topic, List<MessageDto> messageList) {
redisTemplate.convertAndSend(topic.getTopic(), message);
}
}
@Service
@RequiredArgsConstructor
public class RedisSubscriber implements MessageListener {
private final SimpMessagingTemplate messagingTemplate;
@Override
public void onMessage(Message message, byte[] pattern) {
String destination = new String(message.getChannel());
String payload = new String(message.getBody());
log.info("destination: {}, payload: {}", destination, payload);
this.messagingTemplate.convertAndSend(destination, payload);
}
}
메세지를 보낸 객체가 문제인가?
Try1. 메세지 객체를 Map으로 변경
public void publish(ChannelTopic topic, List<MessageDto> messageList) {
List<Map<String, Object>> messageMapList = messageList.stream()
.filter(Objects::nonNull)
.map(this::convertMessageToMap)
.toList();
redisTemplate.convertAndSend(topic.getTopic(), messageMapList);
}
private Map<String, Object> convertMessageToMap(MessageDto message) {
return Map.of(
"id", message.getId(),
"roomId", message.getRoomId(),
"sender", message.getSender() == null ? "CodeChef" : new HashMap<>(
Map.of(
"id", message.getSender().getId(),
"email", message.getSender().getEmail()
)
),
"content", message.getContent(),
"createdAt", message.getCreatedAt()
);
}
subscribe 로그에는 잘 찍히는데 response 응답으로 안 옴.(실패)
리스트라서 그런가?
Try2. Map<String, Map<String, Object>> 로 변경
public void publish(ChannelTopic topic, List<MessageDto> messageList) {
Map<Integer, Map<String, Object>> messageMap = new HashMap<>();
IntStream.range(0, messageList.size())
.forEach(i -> {
messageMap.put(i, this.convertMessageToMap(messageList.get(i)));
});
redisTemplate.convertAndSend(topic.getTopic(), messageMap);
}
로그는 찍히나 response가 안 옴.(실패)
Try3. 객체로 보내지 말고 JSON String으로 보내보자
public void publish(ChannelTopic topic, List<MessageDto> messageList) {
try {
String meesagePayload = objectMapper.writeValueAsString(messageList);
redisTemplate.convertAndSend(topic.getTopic(), messageList);
} catch (JsonProcessingException e) {
throw new ApiException(ErrorStatus.JSON_CHANGE_FAILED);
}
}
역시나 실패!
리스트를 JSON String으로 변환해서 그런가? 하고 Map을 변환해서 보내 보았는데도 마찬가지였음
서비스 클래스에서 데이터 로딩용 주제(topic)를 추가하고 publish하고 바로 주제를 삭제해서 그런가?
구독 주제를 유저별로 고유하게 주고 채팅방 퇴장할 때, 구독 주제를 삭제
/**
* 이전 메세지 로드
* @param roomId : 채팅방 ID
* @param userId : 유저 ID
*/
public void getMessages(Long roomId, Long userId) {
List<WSMessage> messageList = this.wsMessageService.getMessages(roomId);
if (messageList == null || messageList.isEmpty()) {
log.info("init : no message");
return;
}
log.info("init: publish");
ChannelTopic topic = this.chatService.getLoadTopic(roomId, userId);
this.chatService.addTopic(topic);
this.redisPublisher.publish(topic, messageList);
}
/**
* 채팅방 퇴장(구독 취소)
* @param roomId : 채팅방 ID
* @param dto : 방장 승계 정보(success, nextHostId)
* @param chatUser : 퇴장 유저 ID
*/
public void unsubscribeChatRoom(Long roomId, UnsubscribeDTO dto, WSChatUser chatUser) {
ChannelTopic topic = this.chatService.getTopic(roomId);
ChannelTopic initTopic = this.chatService.getLoadTopic(roomId, chatUser.getId());
this.chatService.removeTopic(initTopic);
if (dto.isSuccess() && dto.getNextHostId() == null) {
this.chatService.removeTopic(topic);;
return;
}
List<WSMessage> messageList = this.wsMessageService.unsubscribeChatRoom(roomId, chatUser, dto);
this.redisPublisher.publish(topic, messageList);
}
이것도 실패ㅜㅜ
이제 다른 방법을 못찾겠어서 그냥 리스트의 메세지 하나하나씩 각각 전송해 보았다.
이젠 정말 되겠지… 하고 시도했는데
/**
* 이전 메세지 로드
* @param roomId : 채팅방 ID
* @param userId : 유저 ID
*/
public void getMessages(Long roomId, Long userId) {
List<MessageGetResponse> messageList = this.redisChatRepository.findAllMessageGetResponseById(roomId);
if (messageList.isEmpty()) {
return;
}
ChannelTopic topic = this.chatService.getInitTopic(roomId, userId);
this.chatService.addTopic(topic);
messageList.stream()
.filter(Objects::nonNull)
.forEach(message -> this.redisPublisher.publish(topic, message));
}
이것도 로그만 찍히고 실패!