Skip to content

Commit

Permalink
feat: 채팅 메시지를 토픽으로 전송하고 리스너로 받는 로직 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
kjungw1025 committed Jan 23, 2024
1 parent 994005c commit c2b245d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package com.dku.council.domain.chat.service;

import com.dku.council.domain.chat.model.dto.Message;
import com.dku.council.domain.chat.model.dto.response.ResponseChatDto;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.annotation.KafkaListener;
Expand All @@ -11,13 +14,14 @@
@RequiredArgsConstructor
@Slf4j
public class MessageReceiver {

private final SimpMessageSendingOperations template;

@KafkaListener(topics = "chatting", containerFactory = "kafkaConsumerContainerFactory")
public void receiveMessage(ResponseChatDto message) {
log.info("전송할 채팅방 번호 = /sub/chatRoom/enter" + message.getRoomId(), message);
log.info("채팅방으로 메시지 전송 = {}", message);
public void receiveMessage(String stringChat) throws JsonProcessingException {

ObjectMapper objectMapper = new ObjectMapper();
Message message = objectMapper.readValue(stringChat, Message.class);
log.info("Consumed Message : " + stringChat);

// 메시지 객체 내부의 채팅방 번호를 참조하여, 해당 채팅방 구독자에게 메시지를 발송
template.convertAndSend("/sub/chatRoom/enter" + message.getRoomId(), message);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.dku.council.domain.chat.service;

import com.dku.council.domain.chat.model.dto.Message;
import com.dku.council.domain.chat.model.dto.response.ResponseChatDto;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
Expand All @@ -12,12 +13,19 @@
@RequiredArgsConstructor
@Slf4j
public class MessageSender {
private final KafkaTemplate<String, ResponseChatDto> kafkaTemplate;
private final KafkaTemplate<String, String> kafkaTemplate;

// 메시지를 지정한 Kafka 토픽으로 전송
public void send(String topic, ResponseChatDto data) {
public void send(String topic, Message data) {

// 메시지를 KafkaTemplate 를 사용하여 지정된 토픽으로 전송
kafkaTemplate.send(topic, data);
ObjectMapper objectMapper = new ObjectMapper();
try {
String stringChat = objectMapper.writeValueAsString(data);
log.info("MessageSender Message -> String형 : " + stringChat);
kafkaTemplate.send(topic, stringChat);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}

0 comments on commit c2b245d

Please sign in to comment.