Skip to content

Commit

Permalink
#16 feat: SocketHandler(웹소켓)을 통한 메시지 전송 API(+mongoDB채팅저장,+rabbitMQ로 메…
Browse files Browse the repository at this point in the history
…시지publish) 한번에 되도록 구현
  • Loading branch information
xhaktmchl committed Nov 22, 2022
1 parent a96c6b9 commit b5ac470
Show file tree
Hide file tree
Showing 7 changed files with 64 additions and 38 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import org.springframework.web.socket.handler.TextWebSocketHandler;
import shop.geeksasangchat.dto.PostChattingRes;
import shop.geeksasangchat.rabbitmq.ChattingVO;
import shop.geeksasangchat.service.PartyChattingService;

import java.util.HashMap;

Expand All @@ -20,6 +21,7 @@
public class SocketHandler extends TextWebSocketHandler {
private final RabbitTemplate rabbitTemplate;
private final String EXCHANGE = "chatting-room-exchange-test2";
private final PartyChattingService partyChattingService;

HashMap<String, WebSocketSession> sessionMap = new HashMap<>(); //웹소켓 세션을 담아둘 맵

Expand All @@ -34,30 +36,28 @@ public void handleTextMessage(WebSocketSession session, TextMessage message) {

try {
// ObjectMapper mapper = new ObjectMapper();
ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());
ChattingVO chattingVO = mapper.readValue(msg, ChattingVO.class);
// ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());
// ChattingVO chattingVO = mapper.readValue(msg, ChattingVO.class);

String exchangeName = "chatting-" + "exchange-" + chattingVO.getChattingRoomUUID();

// json 형식으로 변환 후 전송
// ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());
ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());
// PostChattingRes postChattingRes = new PostChattingRes(chattingRoomId, saveChatting.getContent(), saveChatting.getBaseEntity().getCreatedAt()); // ObjectMapper가 java8의 LocalDateTime을 지원하지 않는 에러 해결
// PostChattingRes postChattingRes = mapper.readValue(msg, PostChattingRes.class);
String saveChattingJsonStr = null;
try {
saveChattingJsonStr = mapper.writeValueAsString(chattingVO);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
// for(int i=0;i<participantsCnt;i++){
// rabbitTemplate.convertAndSend(EXCHANGE_NAME, chattingRoomId, saveChattingJsonStr); // convertAndSend(exchange, 라우팅 키, 메시지 내용) : EXCHANGE를 통해 라우팅 키에 해당하는 큐에 메시지 전송.
//// rabbitTemplate.convertAndSend(FANOUT_EXCHANGE_NAME, chattingRoomId, saveChattingJsonStr);
PostChattingRes postChattingRes = mapper.readValue(msg, PostChattingRes.class);

partyChattingService.createChatting(1, postChattingRes.getEmail(), postChattingRes.getChattingRoomId(), postChattingRes.getContent());//TODO: userId 넣는 부분 멤버 엔티티 구현 후 수정
// String exchangeName = "chatting-" + "exchange-" + postChattingRes.getChattingRoomId();
// String saveChattingJsonStr = null;
// try {
// saveChattingJsonStr = mapper.writeValueAsString(postChattingRes);
// } catch (JsonProcessingException e) {
// e.printStackTrace();
// }

rabbitTemplate.convertAndSend(exchangeName, "asd", saveChattingJsonStr);
//
// rabbitTemplate.convertAndSend(exchangeName, "asdf", saveChattingJsonStr);

} catch (Exception e) {

System.out.println("웹소켓 메시지 전송 에러 발생");
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,20 +41,19 @@ public BaseResponse<Long> createPartyChattingRoom(HttpServletRequest request, @R
}

@PostMapping("/chatting")
public BaseResponse<String> createPartyChatting(HttpServletRequest request, @RequestBody PostChattingReq dto){
JwtInfo jwtInfo = (JwtInfo) request.getAttribute("jwtInfo");
System.out.println("dto.getChattingRoomId() = " + dto.getChattingRoomId());
partyChattingService.createChatting(jwtInfo.getUserId(), "tomas", dto.getChattingRoomId(), dto.getContent());
return new BaseResponse("채팅송신을 성공했습니다.");
}
// @NoIntercept //TODO:개발을 위해 임시로 jwt 허용되게한 것. 추후 제거 바람.
// public BaseResponse<String> createPartyChatting(HttpServletRequest request, @RequestBody PostChattingReq dto){
// JwtInfo jwtInfo = (JwtInfo) request.getAttribute("jwtInfo");
//// JwtInfo jwtInfo = (JwtInfo) request.getAttribute("jwtInfo");
// System.out.println("dto.getChattingRoomId() = " + dto.getChattingRoomId());
// partyChattingService.createChatting(jwtInfo.getUserId(), dto.getChattingRoomId(), dto.getContent(), dto.getParticipantsCnt());
// partyChattingService.createChatting(1, dto.getChattingRoomId(), dto.getContent(), dto.getParticipantsCnt());
// return new BaseResponse("채팅송신을 성공했습니다.");
// }
@NoIntercept //TODO:개발을 위해 임시로 jwt 허용되게한 것. 추후 제거 바람.
public BaseResponse<String> createPartyChatting(HttpServletRequest request, @RequestBody PostChattingReq dto){
// JwtInfo jwtInfo = (JwtInfo) request.getAttribute("jwtInfo");
System.out.println("dto.getChattingRoomId() = " + dto.getChattingRoomId());
partyChattingService.createChatting(1, dto.getChattingRoomId(), dto.getContent(), dto.getParticipantsCnt());
return new BaseResponse("채팅송신을 성공했습니다.");
}

/**
* @author 토마스
Expand Down
5 changes: 1 addition & 4 deletions src/main/java/shop/geeksasangchat/dto/PostChattingReq.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,8 @@ public class PostChattingReq {
@NotEmpty
private String content;

private int participantsCnt;

public PostChattingReq(String chattingRoomId, String content, int participantsCnt) {
public PostChattingReq(String chattingRoomId, String content) {
this.chattingRoomId = chattingRoomId;
this.content = content;
this.participantsCnt = participantsCnt;
}
}
13 changes: 13 additions & 0 deletions src/main/java/shop/geeksasangchat/dto/PostChattingRes.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@
@Getter
public class PostChattingRes {

private String chattingId;

private String email;

@NotEmpty
private String chattingRoomId;

Expand All @@ -26,4 +30,13 @@ public PostChattingRes(String chattingRoomId, String content, LocalDateTime crea
this.content = content;
this.createdAt = createdAt;
}

public PostChattingRes(String email, String chattingRoomId, String content, LocalDateTime createdAt) {
this.email = email;
this.chattingRoomId = chattingRoomId;
this.content = content;
this.createdAt = createdAt;
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ public String createChattingRoom(@RequestParam String email, @RequestParam Strin

Binding binding = new Binding(email, Binding.DestinationType.QUEUE, exchangeName, "asdf",null); //TODO: fanoutExchange는 routingKey가 필요없지만 없으면 에러나서 임시로 입력 함.
admin.declareBinding(binding);

return "OK";
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,11 @@ public TopicExchange getTopicExchange() {
}

// publish 메소드: 큐애 메시지 보내기
public void send(Chatting saveChatting, String chattingRoomId, int participantsCnt) {
public void send(Chatting saveChatting, String chattingRoomId) {
System.out.println("====================" + chattingRoomId);
System.out.println("chattingRoomId = " + chattingRoomId);
System.out.println("saveChatting = " + saveChatting);
String exchangeName = "chatting-" + "exchange-" + chattingRoomId;
// json 형식으로 변환 후 전송
ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());
PostChattingRes postChattingRes = new PostChattingRes(chattingRoomId, saveChatting.getContent(), saveChatting.getBaseEntity().getCreatedAt()); // ObjectMapper가 java8의 LocalDateTime을 지원하지 않는 에러 해결
Expand All @@ -51,10 +52,10 @@ public void send(Chatting saveChatting, String chattingRoomId, int participantsC
} catch (JsonProcessingException e) {
e.printStackTrace();
}
for(int i=0;i<participantsCnt;i++){
rabbitTemplate.convertAndSend(EXCHANGE_NAME, chattingRoomId, saveChattingJsonStr); // convertAndSend(exchange, 라우팅 키, 메시지 내용) : EXCHANGE를 통해 라우팅 키에 해당하는 큐에 메시지 전송.

rabbitTemplate.convertAndSend(exchangeName, chattingRoomId, saveChattingJsonStr); // convertAndSend(exchange, 라우팅 키, 메시지 내용) : EXCHANGE를 통해 라우팅 키에 해당하는 큐에 메시지 전송.
// rabbitTemplate.convertAndSend(FANOUT_EXCHANGE_NAME, chattingRoomId, saveChattingJsonStr);
}

}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package shop.geeksasangchat.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.rabbitmq.client.AMQP;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.Queue;
Expand All @@ -13,6 +16,8 @@
import shop.geeksasangchat.common.exception.BaseException;
import shop.geeksasangchat.common.exception.BaseResponseStatus;
import shop.geeksasangchat.domain.*;
import shop.geeksasangchat.dto.PostChattingRes;
import shop.geeksasangchat.rabbitmq.MQController;
import shop.geeksasangchat.rabbitmq.PartyChattingQueue;
import shop.geeksasangchat.repository.ChattingRepository;
import shop.geeksasangchat.repository.ChattingRoomRepository;
Expand All @@ -32,6 +37,7 @@ public class PartyChattingService {
private final ChattingRepository chattingRepository;
private final PartyChattingQueue partyChattingQueue;
private final PartyChattingRoomRepository partyChattingRoomRepository;
private final MQController mqController;

@Transactional(readOnly = false)
public String createChattingRoom(int userId, String title){
Expand All @@ -43,11 +49,22 @@ public String createChattingRoom(int userId, String title){
}

@Transactional(readOnly = false)
public void createChatting(int userId, String chattingRoomId, String content, int participantsCnt) {
public void createChatting(int userId, String email, String chattingRoomId, String content) {
// mongoDB 채팅 저장
Chatting chatting = new Chatting(content);
Chatting saveChatting = chattingRepository.save(chatting);
partyChattingQueue.send(saveChatting, chattingRoomId, participantsCnt); // 저장한 채팅 rabbitmq를 이용해 Consumer에게 메시지 전송

// partyChattingQueue.send(saveChatting, chattingRoomId); // 저장한 채팅 rabbitmq를 이용해 Consumer에게 메시지 전송

// json 형식으로 변환 후 RabbitMQ 전송
ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());
PostChattingRes postChattingRes = new PostChattingRes(email, chattingRoomId, saveChatting.getContent(), saveChatting.getBaseEntity().getCreatedAt()); // ObjectMapper가 java8의 LocalDateTime을 지원하지 않는 에러 해결
String saveChattingJsonStr = null;
try {
saveChattingJsonStr = mapper.writeValueAsString(postChattingRes);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
mqController.sendMessage(saveChattingJsonStr, chattingRoomId); // rabbitMQ 메시지 publish
}

@Transactional(readOnly = false)
Expand Down

0 comments on commit b5ac470

Please sign in to comment.