Skip to content

Commit

Permalink
Merge pull request #126 from catchroom/#98/채팅방리스트리팩토링
Browse files Browse the repository at this point in the history
Refactor : ChatRoom 리팩토링
  • Loading branch information
HyemIin authored Feb 9, 2024
2 parents 465db8f + 68e50a9 commit 8d7e6b7
Show file tree
Hide file tree
Showing 9 changed files with 74 additions and 83 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.catchroom.chat.chatroom.controller;

import com.catchroom.chat.chatroom.dto.ChatRoomListGetResponse;
import com.catchroom.chat.chatroom.dto.ChatRoomGetResponse;
import com.catchroom.chat.chatroom.service.ChatRoomService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
Expand All @@ -17,16 +17,16 @@ public class ChatRoomController {
//TODO 같은게 2개..? getChatRoomList에 모든 정보가 다 담기는데 왜??

@GetMapping("/list")
public List<ChatRoomListGetResponse> getChatRoomList(
public List<ChatRoomGetResponse> getChatRoomList(
@RequestHeader("Authorization") String accessToken,
@RequestParam(name = "userId") Long userId
) {
return chatRoomService.getChatRoomListByHttp(userId, accessToken);
return chatRoomService.getChatRoomListByFeign(userId, accessToken);
}


@GetMapping("/info")
public ChatRoomListGetResponse getChatRoom(
public ChatRoomGetResponse getChatRoom(
@RequestHeader("Authorization") String accessToken,
@RequestParam(name = "roomId") String roomId
) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
public class ChatRoomListGetResponse implements Serializable {
public class ChatRoomGetResponse implements Serializable {
private String chatRoomNumber;

private Long buyerId;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.catchroom.chat.chatroom.service;

import com.catchroom.chat.chatroom.dto.ChatRoomListGetResponse;
import com.catchroom.chat.chatroom.dto.ChatRoomGetResponse;
import com.catchroom.chat.feign.client.MainFeignClient;
import com.catchroom.chat.global.common.SuccessMessage;
import com.catchroom.chat.message.dto.ChatMessageDto;
Expand All @@ -23,28 +23,24 @@ public class ChatRoomService {
private final ChatRoomRedisRepository chatRoomRedisRepository;
private final ChatMongoService chatMongoService;

public ChatRoomListGetResponse getChatRoomInfo(String accessToken, String roomId) {
public ChatRoomGetResponse getChatRoomInfo(String accessToken, String roomId) {
return mainFeignClient.getChatRoomInfo(accessToken, roomId);
}

public List<ChatRoomListGetResponse> getChatRoomListByHttp(Long userId, String accessToken) {
public List<ChatRoomGetResponse> getChatRoomListByFeign(Long userId, String accessToken) {
// 처음 HTTP 요청에서는 무조건 레디스 초기화 진행하도록 로직 수정
List<ChatRoomListGetResponse> chatRoomListGetResponseList = mainFeignClient.getChatRoomList(accessToken);
List<ChatRoomGetResponse> chatRoomListGetResponseList = mainFeignClient.getChatRoomList(accessToken);
chatRoomListGetResponseList.forEach(this::setListChatLastMessage);
chatRoomRedisRepository.initChatRoomList(userId, chatRoomListGetResponseList);
return sortChatRoomListLatest(chatRoomListGetResponseList);
}

public List<ChatRoomGetResponse> getChatRoomList(Long userId, String accessToken) {



public List<ChatRoomListGetResponse> getChatRoomList(Long userId, String accessToken) {

List<ChatRoomListGetResponse> chatRoomListGetResponseList = null;
List<ChatRoomGetResponse> chatRoomListGetResponseList = null;
if (chatRoomRedisRepository.existChatRoomList(userId)) {
chatRoomListGetResponseList = chatRoomRedisRepository.getChatRoomList(userId);


} else {
// 채팅방이 레디스에 없으면 페인 사용해서 불러온다!
chatRoomListGetResponseList = mainFeignClient.getChatRoomList(accessToken);
Expand All @@ -56,16 +52,14 @@ public List<ChatRoomListGetResponse> getChatRoomList(Long userId, String accessT
return chatRoomListGetResponseList;
}


/**
* 몽고 디비에서 마지막 메시지 가져와서 저장하는 로직
* @param chatRoomListGetResponse
*/
public void setListChatLastMessage(ChatRoomListGetResponse chatRoomListGetResponse) {
public void setListChatLastMessage(ChatRoomGetResponse chatRoomListGetResponse) {

// 몽고 디비에서 마지막 메시지 가져와서 저장.
String chatRoomNumber = chatRoomListGetResponse.getChatRoomNumber();
//TODO 레디스에 마지막 메세지가 없으면??
if (chatRoomRedisRepository.getLastMessage(chatRoomNumber) != null) {
chatRoomListGetResponse.updateChatMessageDto(
chatRoomRedisRepository.getLastMessage(chatRoomNumber)
Expand All @@ -84,11 +78,11 @@ public void setListChatLastMessage(ChatRoomListGetResponse chatRoomListGetRespon
* 채팅방 마지막 메시지의 시간들을 비교하여 정렬하는 메소드
* @param chatRoomListGetResponseList
*/
public List<ChatRoomListGetResponse> sortChatRoomListLatest (
List<ChatRoomListGetResponse> chatRoomListGetResponseList
public List<ChatRoomGetResponse> sortChatRoomListLatest (
List<ChatRoomGetResponse> chatRoomListGetResponseList
) {
List<ChatRoomListGetResponse> newChatRoomList = new ArrayList<>();
for (ChatRoomListGetResponse response : chatRoomListGetResponseList) {
List<ChatRoomGetResponse> newChatRoomList = new ArrayList<>();
for (ChatRoomGetResponse response : chatRoomListGetResponseList) {
if (response.getLastChatmessageDto() != null) newChatRoomList.add(response);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.catchroom.chat.feign.client;

import com.catchroom.chat.chatroom.dto.ChatRoomListGetResponse;
import com.catchroom.chat.chatroom.dto.ChatRoomGetResponse;
import com.catchroom.chat.global.common.SuccessMessage;
import com.catchroom.chat.global.config.FeignConfig;
import com.catchroom.chat.feign.dto.AccommodationResponse;
Expand Down Expand Up @@ -29,11 +29,11 @@ public interface MainFeignClient {
@RequestMapping(method = RequestMethod.GET, value = "/accommodation/{accommodationId}")
AccommodationResponse getAccommodationDto(@PathVariable Long accommodationId);

@RequestMapping(method = RequestMethod.GET, value = "/chat/room/list/chat")
List<ChatRoomListGetResponse> getChatRoomList(@RequestHeader("Authorization") String accessToken);
@RequestMapping(method = RequestMethod.GET, value = "/chat/room/list/feign")
List<ChatRoomGetResponse> getChatRoomList(@RequestHeader("Authorization") String accessToken);

@RequestMapping(method = RequestMethod.GET, value = "/chat/room/info")
ChatRoomListGetResponse getChatRoomInfo(
ChatRoomGetResponse getChatRoomInfo(
@RequestHeader("Authorization") String accessToken,
@RequestParam(name = "roomId") String roomId
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.catchroom.chat.global.pubsub;

import com.catchroom.chat.chatroom.dto.ChatRoomListGetResponse;
import com.catchroom.chat.chatroom.dto.ChatRoomGetResponse;
import com.catchroom.chat.message.dto.ChatMessageDto;
import com.catchroom.chat.message.dto.MessageSubDto;
import com.fasterxml.jackson.databind.ObjectMapper;
Expand Down Expand Up @@ -48,8 +48,8 @@ public void sendRoomList(String publishMessage) {

ChatMessageDto chatMessage = dto.getChatMessageDto();

List<ChatRoomListGetResponse> chatRoomListGetResponseList = dto.getList();
List<ChatRoomListGetResponse> chatRoomListGetResponseListPartner = dto.getPartnerList();
List<ChatRoomGetResponse> chatRoomListGetResponseList = dto.getList();
List<ChatRoomGetResponse> chatRoomListGetResponseListPartner = dto.getPartnerList();

Long userId = dto.getUserId();
Long partnerId = dto.getPartnerId();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.catchroom.chat.message.dto;

import com.catchroom.chat.chatroom.dto.ChatRoomListGetResponse;
import com.catchroom.chat.chatroom.dto.ChatRoomGetResponse;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
Expand All @@ -15,6 +15,6 @@ public class MessageSubDto implements Serializable {
private Long userId;
private Long partnerId;
private ChatMessageDto chatMessageDto;
private List<ChatRoomListGetResponse> list;
private List<ChatRoomListGetResponse> partnerList;
private List<ChatRoomGetResponse> list;
private List<ChatRoomGetResponse> partnerList;
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.catchroom.chat.message.repository;

import com.catchroom.chat.chatroom.dto.ChatRoomListGetResponse;
import com.catchroom.chat.chatroom.dto.ChatRoomGetResponse;
import com.catchroom.chat.message.dto.ChatMessageDto;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
Expand Down Expand Up @@ -29,7 +29,7 @@ public class ChatRoomRedisRepository {
private final ObjectMapper objectMapper;

@Resource(name = "redisTemplate")
private HashOperations<String, String, ChatRoomListGetResponse> opsHashChatRoom;
private HashOperations<String, String, ChatRoomGetResponse> opsHashChatRoom;

@Resource(name = "redisTemplate")
private HashOperations<String, String, ChatMessageDto> opsHashLastChatMessage;
Expand All @@ -43,19 +43,19 @@ public boolean existChatRoomList(Long userId) {
return redisTemplate.hasKey(getChatRoomKey(userId));
}

public void initChatRoomList(Long userId, List<ChatRoomListGetResponse> list) {
public void initChatRoomList(Long userId, List<ChatRoomGetResponse> list) {
if (redisTemplate.hasKey(getChatRoomKey(userId))) {
redisTemplate.delete(getChatRoomKey(userId));
}

opsHashChatRoom = redisTemplate.opsForHash();
for (ChatRoomListGetResponse chatRoomListGetRes : list) {
for (ChatRoomGetResponse chatRoomListGetRes : list) {
setChatRoom(userId, chatRoomListGetRes.getChatRoomNumber(), chatRoomListGetRes);
}

}

public void setChatRoom(Long userId, String roomId, ChatRoomListGetResponse response) {
public void setChatRoom(Long userId, String roomId, ChatRoomGetResponse response) {
opsHashChatRoom.put(getChatRoomKey(userId), roomId, response);
}

Expand All @@ -67,11 +67,11 @@ public void deleteChatRoom(Long userId, String roomId) {
opsHashChatRoom.delete(getChatRoomKey(userId), roomId);
}

public ChatRoomListGetResponse getChatRoom(Long userId, String roomId) {
return objectMapper.convertValue(opsHashChatRoom.get(getChatRoomKey(userId), roomId), ChatRoomListGetResponse.class);
public ChatRoomGetResponse getChatRoom(Long userId, String roomId) {
return objectMapper.convertValue(opsHashChatRoom.get(getChatRoomKey(userId), roomId), ChatRoomGetResponse.class);
}

public List<ChatRoomListGetResponse> getChatRoomList(Long userId) {
public List<ChatRoomGetResponse> getChatRoomList(Long userId) {
return objectMapper.convertValue(opsHashChatRoom.values(getChatRoomKey(userId)), new TypeReference<>() {});
}

Expand Down
75 changes: 36 additions & 39 deletions src/main/java/com/catchroom/chat/message/service/ChatService.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.catchroom.chat.message.service;

import com.catchroom.chat.chatroom.dto.ChatRoomListGetResponse;
import com.catchroom.chat.chatroom.dto.ChatRoomGetResponse;
import com.catchroom.chat.chatroom.service.ChatRoomService;
import com.catchroom.chat.message.dto.ChatMessageDto;
import com.catchroom.chat.global.pubsub.RedisPublisher;
Expand Down Expand Up @@ -41,53 +41,48 @@ public String getRoomId(String destination) {
* 채팅방에 메시지 발송
*/
public void sendChatMessage(ChatMessageDto chatMessage, String accessToken) {
//TODO 이거 중복??아래에서 하지 않나?
chatRoomRedisRepository.setLastChatMessage(chatMessage.getRoomId(), chatMessage);

Long userId = chatMessage.getUserId();
Long partnerId;

// 1. 채팅방이 삭제되는 것이라면 delete 를 해준다.
// 1. 채팅방이 삭제되는 것이라면 채팅방을 delete 해준다.
if (chatMessage.getType().equals(MessageType.DELETE)) {
chatRoomService.deleteChatRoom(accessToken, chatMessage.getRoomId(), userId);
//TODO 레디스에서도 삭제 필요??
chatRoomRedisRepository.deleteChatRoom(userId,chatMessage.getRoomId());
}

ChatRoomListGetResponse newChatRoomList = null;
// 2. 채팅방 리스트에 새로운 채팅방 정보가 없다면, 넣어준다. 마지막 메시지도 같이 담는다. 상대방 레디스에도 업데이트 해준다.
ChatRoomGetResponse newChatRoom = null;
if (chatRoomRedisRepository.existChatRoom(userId, chatMessage.getRoomId())) {
newChatRoomList = chatRoomRedisRepository.getChatRoom(userId, chatMessage.getRoomId());
newChatRoom = chatRoomRedisRepository.getChatRoom(userId, chatMessage.getRoomId());
} else {
newChatRoomList = chatRoomService.getChatRoomInfo(accessToken, chatMessage.getRoomId());
newChatRoom = chatRoomService.getChatRoomInfo(accessToken, chatMessage.getRoomId());
}

partnerId = getPartnerId(chatMessage, newChatRoomList);

// 2. 채팅방 리스트에 새로운 채팅방 정보가 없다면, 넣어준다. 마지막 메시지도 같이 담는다. 상대방 레디스에도 업데이트 해준다.
setNewChatRoomInfo(chatMessage, newChatRoomList);
partnerId = getPartnerId(chatMessage, newChatRoom);
setNewChatRoomInfo(chatMessage, newChatRoom);

// 3. 마지막 메시지들이 담긴 채팅방 리스트들을 가져온다. // 4. 파트너 채팅방 리스트도 가져온다. (파트너는 userId 로만)
List<ChatRoomListGetResponse> chatRoomListGetResponseList = chatRoomService.getChatRoomList(userId, accessToken);
List<ChatRoomListGetResponse> partnerChatRoomGetResponseList = getChatRoomListByUserId(partnerId);
List<ChatRoomGetResponse> chatRoomList = chatRoomService.getChatRoomList(userId, accessToken);
List<ChatRoomGetResponse> partnerChatRoomList = getChatRoomListByPartnerId(partnerId);

// 5. 마지막 메세지 기준으로 정렬 채팅방 리스트 정렬
chatRoomListGetResponseList = chatRoomService.sortChatRoomListLatest(chatRoomListGetResponseList);
partnerChatRoomGetResponseList = chatRoomService.sortChatRoomListLatest(partnerChatRoomGetResponseList);
chatRoomList = chatRoomService.sortChatRoomListLatest(chatRoomList);
partnerChatRoomList = chatRoomService.sortChatRoomListLatest(partnerChatRoomList);

MessageSubDto messageSubDto = MessageSubDto.builder()
.userId(userId)
.partnerId(partnerId)
.chatMessageDto(chatMessage)
.list(chatRoomListGetResponseList)
.partnerList(partnerChatRoomGetResponseList)
.list(chatRoomList)
.partnerList(partnerChatRoomList)
.build();

redisPublisher.publish(messageSubDto);
}

private Long getPartnerId(ChatMessageDto chatMessageDto, ChatRoomListGetResponse my) {
Long userId = chatMessageDto.getUserId();
private Long getPartnerId(ChatMessageDto chatMessageDto, ChatRoomGetResponse my) {
Long partnerId;
if (my.getBuyerId() == userId) {
if (my.getBuyerId() == chatMessageDto.getUserId()) {
partnerId = my.getSellerId();
} else {
partnerId = my.getBuyerId();
Expand All @@ -100,42 +95,44 @@ private Long getPartnerId(ChatMessageDto chatMessageDto, ChatRoomListGetResponse
* redis 에 채팅방 정보가 없는 경우 새로 저장.
* @param chatMessage
*/
private void setNewChatRoomInfo(ChatMessageDto chatMessage, ChatRoomListGetResponse newChatRoomListResponse) {
private void setNewChatRoomInfo(ChatMessageDto chatMessage, ChatRoomGetResponse newChatRoom) {

newChatRoomListResponse.updateChatMessageDto(chatMessage);
newChatRoom.updateChatMessageDto(chatMessage);

/** 상대방 채팅 리스트와 내 리스트 둘다 채팅방을 저장한다. */

if (newChatRoomListResponse.getLoginUserIdentity().equals(UserIdentity.SELLER)) {
// 1. 로그인 유저가 seller라면 지금 전송한 메세지를 레디스에 최신메세지로 저장한다.
if (newChatRoom.getLoginUserIdentity().equals(UserIdentity.SELLER)) {
if (!chatMessage.getType().equals(MessageType.DELETE)) {
chatRoomRedisRepository.setChatRoom(newChatRoomListResponse.getSellerId(),
chatMessage.getRoomId(), newChatRoomListResponse);
chatRoomRedisRepository.setChatRoom(newChatRoom.getSellerId(),
chatMessage.getRoomId(), newChatRoom);
}
newChatRoomListResponse.changePartnerInfo(); //닉네임 체인지
chatRoomRedisRepository.setChatRoom(newChatRoomListResponse.getBuyerId(), chatMessage.getRoomId(), newChatRoomListResponse);
newChatRoom.changePartnerInfo(); //닉네임 체인지
chatRoomRedisRepository.setChatRoom(newChatRoom.getBuyerId(),
chatMessage.getRoomId(), newChatRoom);

} else if (newChatRoomListResponse.getLoginUserIdentity().equals(UserIdentity.BUYER)){
} else if (newChatRoom.getLoginUserIdentity().equals(UserIdentity.BUYER)){
if (!chatMessage.getType().equals(MessageType.DELETE)) {
chatRoomRedisRepository.setChatRoom(newChatRoomListResponse.getBuyerId(),
chatMessage.getRoomId(), newChatRoomListResponse);
chatRoomRedisRepository.setChatRoom(newChatRoom.getBuyerId(),
chatMessage.getRoomId(), newChatRoom);
}

newChatRoomListResponse.changePartnerInfo(); //닉네임 체인지
chatRoomRedisRepository.setChatRoom(newChatRoomListResponse.getSellerId(), chatMessage.getRoomId(), newChatRoomListResponse);
newChatRoom.changePartnerInfo(); //닉네임 체인지
chatRoomRedisRepository.setChatRoom(newChatRoom.getSellerId(),
chatMessage.getRoomId(), newChatRoom);
}

//다시 원상태로 복귀
newChatRoomListResponse.changePartnerInfo();
newChatRoom.changePartnerInfo();

}

// redis에서 채팅방 리스트 불러오는 로직
private List<ChatRoomListGetResponse> getChatRoomListByUserId(Long userId) {
List<ChatRoomListGetResponse> chatRoomListGetResponseList = new ArrayList<>();
private List<ChatRoomGetResponse> getChatRoomListByPartnerId(Long userId) {
List<ChatRoomGetResponse> chatRoomListGetResponseList = new ArrayList<>();

if (chatRoomRedisRepository.existChatRoomList(userId)) {
chatRoomListGetResponseList = chatRoomRedisRepository.getChatRoomList(userId);
for (ChatRoomListGetResponse chatRoomListGetResponse : chatRoomListGetResponseList) {
for (ChatRoomGetResponse chatRoomListGetResponse : chatRoomListGetResponseList) {
chatRoomService.setListChatLastMessage(chatRoomListGetResponse);
}
}
Expand Down
Loading

0 comments on commit 8d7e6b7

Please sign in to comment.