Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEAT] stomp 세션 관리 기능 추가 #91

Merged
merged 1 commit into from
Feb 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 24 additions & 14 deletions src/main/java/com/wooyeon/yeon/chat/controller/StompController.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@
import lombok.RequiredArgsConstructor;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequiredArgsConstructor
Expand All @@ -26,6 +26,7 @@ public class StompController {
private final FcmService fcmService;
private final UserRepository userRepository;

private Map<Long, Long> sessionStore = new ConcurrentHashMap<>();

/*
/queue/chat/room/{matchId} - 채팅방 메시지 URL
Expand All @@ -34,26 +35,35 @@ public class StompController {
*/

@MessageMapping("/chat/message")
public void enter(StompDto stompDto, WebSocketSession session, StompHeaderAccessor accessor) {
public void enter(StompDto stompDto) {
String loginEmail = securityService.getCurrentUserEmail();
session.getAttributes().put(loginEmail, accessor.getUser().getName());
simpMessageSendingOperations.convertAndSend("/queue/chat/room/" + stompDto.getRoomId(), stompDto);
Long roomId = stompDto.getRoomId();

int sessionCount = chatService.calculateUserCount();
if (stompDto.getType().equals(StompDto.MessageType.ENTER.toString())) {
if (!sessionStore.containsKey(roomId) || 0 == sessionStore.get(roomId)) {
sessionStore.put(roomId, 1l);
} else if (1 == sessionStore.get(roomId)) {
sessionStore.put(roomId, 2l);
}
}

if(1 == sessionCount) {
if (stompDto.getType().equals(StompDto.MessageType.TALK.toString())) {
simpMessageSendingOperations.convertAndSend("/queue/chat/room/" + stompDto.getRoomId(), stompDto);
}

if (stompDto.getType().equals(StompDto.MessageType.QUIT.toString())) {
Long sessionCount = sessionStore.get(roomId);
sessionCount -= 1;
sessionStore.put(roomId, sessionCount);
}

if (1 == sessionStore.get(roomId)) {
try {
fcmService.sendMessageTo(FcmDto.buildRequest(loginEmail, stompDto, userRepository));
} catch (IOException e) {
throw new WooyeonException(ExceptionCode.FCM_SEND_FAIL_ERROR);
}
}

chatService.saveChat(stompDto);
}

@MessageMapping("/unsubscribe")
public void handleUnsubscription(WebSocketSession session) {
session.getAttributes().remove(securityService.getCurrentUserEmail());
chatService.saveChat(stompDto, sessionStore);
}
}
5 changes: 5 additions & 0 deletions src/main/java/com/wooyeon/yeon/chat/dto/StompDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,9 @@
public class StompDto {
private Long roomId;
private String message;
private String type;

public enum MessageType {
ENTER, QUIT, TALK
}
}
21 changes: 9 additions & 12 deletions src/main/java/com/wooyeon/yeon/chat/service/ChatService.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,12 @@
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.socket.WebSocketSession;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CopyOnWriteArrayList;

@Service
@RequiredArgsConstructor
Expand All @@ -34,19 +33,23 @@ public class ChatService {
private final UserRepository userRepository;
private final ProfileRepository profileRepository;

private final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

@Transactional
public void saveChat(StompDto stompDto) {
public void saveChat(StompDto stompDto, Map<Long, Long> sessionStore) {
UserMatch userMatch = matchRepository.findById(stompDto.getRoomId())
.orElseThrow(() -> new WooyeonException(ExceptionCode.USER_MATCH_NOT_FOUND));

boolean flag = false;

if(2 == sessionStore.get(stompDto.getRoomId())) {
flag = true;
}

Chat chat = Chat.builder()
.message(stompDto.getMessage())
.sendTime(LocalDateTime.now())
.userMatch(userMatch)
.sender(getLoginUserNickName())
// .isChecked() //stomp 연결되어 있으면 check
.isChecked(flag) //stomp 연결되어 있으면 check
.build();

chatRepository.save(chat);
Expand Down Expand Up @@ -95,10 +98,4 @@ public String getLoginUserNickName() {

return loginUserNickname;
}

public int calculateUserCount() {
// 중복된 사용자를 고려하여 사용자 수를 계산
return (int) sessions.stream().map(s -> s.getAttributes().get("userId")).distinct().count();
}

}