Skip to content

Commit

Permalink
feat: WebSocket으로 채팅 기능(만) 완료 #81
Browse files Browse the repository at this point in the history
  • Loading branch information
yhpark95 committed Sep 20, 2023
1 parent 51dbc5c commit 26e6e69
Show file tree
Hide file tree
Showing 13 changed files with 90 additions and 143 deletions.
2 changes: 1 addition & 1 deletion be/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ dependencies {

// webSocket
implementation 'org.springframework.boot:spring-boot-starter-websocket'
implementation 'org.webjars:stomp-websocket'
implementation 'org.webjars:stomp-websocket:2.3.4'
}

tasks.named('test') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import kr.codesquad.chat.dto.ChatRoomCreateRequest;
import kr.codesquad.chat.dto.request.ChatRoomCreateRequest;
import kr.codesquad.chat.dto.response.ChatRoomCreateResponse;
import kr.codesquad.chat.service.ChatService;
import kr.codesquad.util.Constants;
import lombok.RequiredArgsConstructor;
Expand All @@ -19,12 +20,13 @@ public class ChatController {

private final ChatService chatService;

@PostMapping("/")
public ResponseEntity<Void> createChatRoom(@RequestBody ChatRoomCreateRequest chatRoomCreateRequest,
@PostMapping("/api/chat")
public ResponseEntity<ChatRoomCreateResponse> createChatRoom(
@RequestBody ChatRoomCreateRequest chatRoomCreateRequest,
HttpServletRequest request) {
String loginId = (String)request.getAttribute(Constants.LOGIN_ID);
chatService.createRoom(chatRoomCreateRequest, loginId);
return ResponseEntity.status(HttpStatus.CREATED).build();
return ResponseEntity.status(HttpStatus.CREATED)
.body(chatService.createRoom(chatRoomCreateRequest, loginId));
}

}
5 changes: 5 additions & 0 deletions be/src/main/java/kr/codesquad/chat/dto/ChatMapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;

import kr.codesquad.chat.dto.request.ChatRoomCreateRequest;
import kr.codesquad.chat.dto.response.ChatRoomCreateResponse;
import kr.codesquad.chat.entity.ChatRoom;

@Mapper
Expand All @@ -12,4 +14,7 @@ public interface ChatMapper {

@Mapping(target = "senderId", source = "userId")
ChatRoom toChatRoom(ChatRoomCreateRequest chatRoomCreateRequest, Long userId);

@Mapping(target = "chatRoomId", source = "id")
ChatRoomCreateResponse toChatRoomCreateResponse(ChatRoom chatRoom);
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package kr.codesquad.chat.dto;
package kr.codesquad.chat.dto.request;

import lombok.Getter;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package kr.codesquad.chat.dto.request;

import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@NoArgsConstructor
public class SendMessageRequest {
private Long chatRoomId;
private Long senderId;
private String content;

@Builder
public SendMessageRequest(Long chatRoomId, Long senderId, String content) {
this.chatRoomId = chatRoomId;
this.senderId = senderId;
this.content = content;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package kr.codesquad.chat.dto.response;

import lombok.Builder;
import lombok.Getter;

@Getter
@Builder
public class ChatRoomCreateResponse {
private final Long chatRoomId;
}
41 changes: 38 additions & 3 deletions be/src/main/java/kr/codesquad/chat/service/ChatService.java
Original file line number Diff line number Diff line change
@@ -1,26 +1,61 @@
package kr.codesquad.chat.service;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import com.fasterxml.jackson.databind.ObjectMapper;

import kr.codesquad.chat.dto.ChatMapper;
import kr.codesquad.chat.dto.ChatRoomCreateRequest;
import kr.codesquad.chat.dto.request.ChatRoomCreateRequest;
import kr.codesquad.chat.dto.request.SendMessageRequest;
import kr.codesquad.chat.dto.response.ChatRoomCreateResponse;
import kr.codesquad.chat.repository.ChatMessageRepository;
import kr.codesquad.chat.repository.ChatRoomRepository;
import kr.codesquad.user.entity.User;
import kr.codesquad.user.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RequiredArgsConstructor
@Service
public class ChatService {

private final ChatRoomRepository chatRoomRepository;
private final ChatMessageRepository chatMessageRepository;
private final UserRepository userRepository;
private final ObjectMapper objectMapper;
private final ConcurrentMap<Long, Set<WebSocketSession>> sessionMap = new ConcurrentHashMap<>();

public void createRoom(ChatRoomCreateRequest chatRoomCreateRequest, String loginId) {
public ChatRoomCreateResponse createRoom(ChatRoomCreateRequest chatRoomCreateRequest, String loginId) {
User user = userRepository.findByLoginId(loginId);
chatRoomRepository.save(ChatMapper.INSTANCE.toChatRoom(chatRoomCreateRequest, user.getId()));
return ChatMapper.INSTANCE.toChatRoomCreateResponse(
chatRoomRepository.save(ChatMapper.INSTANCE.toChatRoom(chatRoomCreateRequest, user.getId())));
}

public void sendMessage(Long chatRoomId, WebSocketSession session, SendMessageRequest message) {
if (!sessionMap.containsKey(chatRoomId)) {
sessionMap.put(chatRoomId, new HashSet<>());
}
Set<WebSocketSession> sessions = sessionMap.get(chatRoomId);
sessions.add(session);
sessionMap.put(chatRoomId, sessions);
sessions.parallelStream().forEach(s -> sendMessage(s, message));
}

private <T> void sendMessage(WebSocketSession session, T message) {
try {
session.sendMessage(new TextMessage(objectMapper.writeValueAsString(message)));
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}

}
12 changes: 0 additions & 12 deletions be/src/main/java/kr/codesquad/core/websocket/Message.java

This file was deleted.

29 changes: 0 additions & 29 deletions be/src/main/java/kr/codesquad/core/websocket/MsgController.java

This file was deleted.

33 changes: 0 additions & 33 deletions be/src/main/java/kr/codesquad/core/websocket/MsgRoom.java

This file was deleted.

52 changes: 0 additions & 52 deletions be/src/main/java/kr/codesquad/core/websocket/MsgService.java

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

import com.fasterxml.jackson.databind.ObjectMapper;

import kr.codesquad.chat.dto.request.SendMessageRequest;
import kr.codesquad.chat.service.ChatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

Expand All @@ -15,16 +17,15 @@
@RequiredArgsConstructor
public class WebSocketHandler extends TextWebSocketHandler {

private final MsgService msgService;
private final ChatService chatService;
private final ObjectMapper objectMapper;

@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String payload = message.getPayload();
log.info("payload:{}", payload);

Message msg = objectMapper.readValue(payload, Message.class);
MsgRoom room = msgService.findById(msg.getRoomId());
room.handleActions(session, msg, msgService);
SendMessageRequest msg = objectMapper.readValue(payload, SendMessageRequest.class);
chatService.sendMessage(msg.getChatRoomId(), session, msg);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package kr.codesquad.item.repository;

import static kr.codesquad.chat.entity.QChat.*;
import static kr.codesquad.chat.entity.QChatRoom.*;
import static kr.codesquad.favorite.entity.QFavorite.*;
import static kr.codesquad.item.entity.QItem.*;

Expand Down Expand Up @@ -33,12 +33,12 @@ public List<ItemListVo> readByConditions(ItemConditions itemConditions) {
item.createdAt,
item.price,
item.status,
chat.countDistinct().as("chat"),
chatRoom.countDistinct().as("chat"),
favorite.countDistinct().as("favorite"),
item.userId
))
.from(item)
.leftJoin(chat).on(item.id.eq(chat.itemId))
.leftJoin(chatRoom).on(item.id.eq(chatRoom.itemId))
.leftJoin(favorite).on(item.id.eq(favorite.itemId))
.where(lessThanItemId(itemConditions.getItemId()), equalLocationName(itemConditions.getLocationName())
, equalCategoryId(itemConditions.getCategoryId()), checkStatus(itemConditions.getIsSold())
Expand Down

0 comments on commit 26e6e69

Please sign in to comment.