본문 바로가기

생각정리/사이드 프로젝트

사이드 프로젝트 : 중고 거래 플랫폼 - 웹 소켓 백엔드 설정

의존성 추가

implementation 'org.springframework.boot:spring-boot-starter-websocket'

WebsocketConfig 설정

WebSocketMessageBrokerConfigurer를 구현하여 사용한다.

메서드 설명
addArgumentResolvers 사용자 지정 컨트롤러 메서드 인수 유형을 지원하는 확인자를 추가합니다.
addReturnValueHandlers 사용자 정의 컨트롤러 메서드 반환 값 유형을 지원하는 핸들러를 추가합니다.
configureClientInboundChannel WebSocket 클라이언트에서 들어오는 메시지에 사용되는 구성을 구성합니다 .
configureClientOutboundChannel WebSocket 클라이언트에 대한 아웃바운드 메시지에 사용되는 항목을 구성합니다.
configureMessageBroker 메시지 브로커 옵션을 구성합니다.
configureMessageConverters 주석이 달린 메서드에서 메시지 페이로드를 추출하고 메시지를 보낼 때 사용할 메시지 변환기를 구성합니다
처음에는 비어 있는 제공된 목록을 사용하여 메시지 변환기를 추가할 수 있으며 부울 반환 값은 기본 메시지도 추가해야 하는지 결정하는 데 사용됩니다.
configureWebSocketTransport WebSocket 클라이언트와 주고받는 메시지 처리와 관련된 옵션을 구성합니다.
registerStompEndponts 각각을 특정 URL에 매핑하고 (선택적으로) SockJS 폴백 옵션을 활성화 및 구성하는 STOMP 엔드포인트를 등록합니다.
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 웹 소켓이 handshake를 하기 위해 연결하는 endpoint
        // sockJS Fallback 옵션 활성화
        // sockJS를 사용할 경우, 요청을 보낼 때 - 설정한 endpoint/websocket 으로 작동한다.
        registry.addEndpoint("/chat")
                .setAllowedOriginPatterns("*")
                .withSockJS();
    }

    // 메시지 브로커 설정
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 웹소켓을 통해 보내진 메시지를 가저오기 위한 주소 설정
        registry.enableSimpleBroker("/topic");

        // 클라이언트에서 서버로 메시지를 보내기 위한 주소 설정
        registry.setApplicationDestinationPrefixes("/app");
    }
}
일단은 기본적으로 웹소켓을 이용해서 메시지를 보내고 받는 걸 구현하는 것을 목적으로 웹 소켓 엔드포인트 설정과 메시지 브로커 설정만 사용하기로 하고 나머지 기능들은 차후에 자세히 알아보도록 하기로 했다.

Controller 

@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class ChatController {

    private final ChatService chatService;

    @PostMapping("/chatRoom")
    public void createRoom(@RequestBody ChatRequestDto requestDto, @AuthenticationPrincipal UserDetailsImpl userDetails) {
        chatService.createRoom(requestDto, userDetails.getUser());
    }

    @MessageMapping("/sendMessage") // 메시지 밸행, url 앞에 /pub 생략
    public void sendMessage(@Payload ChatRequestDto requestDto) {
        chatService.saveMessage(requestDto);
    }
}

service

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class ChatService {

    // 특정 broker로 메시지를 전달
    private final SimpMessageSendingOperations template;
    private final ChatRoomRepository chatRoomRepository;
    private final ChatMessageRepository chatMessageRepository;
    private final UserRepository userRepository;

    @Transactional
    public void createRoom(ChatRequestDto requestDto, User user) {
        User seller = findUserByUserId(requestDto.getUserId());
        ChattingRoom chattingRome = new ChattingRoom(seller, user);

        chatRoomRepository.save(chattingRome);

        requestDto.setMessage(user.getUser_nm() + "님 입장!!");
        template.convertAndSend("/topic/chatroom/" + chattingRome.getId(), requestDto);
    }

    @Transactional
    public void saveMessage(ChatRequestDto requestDto) {
        ChattingRoom chattingRoom = findChattingRoom(requestDto.getRoomId());
        User user = findUserByUserId(requestDto.getUserId());

        ChattingMessage chattingMessage = new ChattingMessage(user, requestDto);
        chattingMessage.addChattingRoom(chattingRoom);
        chatMessageRepository.save(chattingMessage);

        requestDto.setUserName(user.getUser_nm());
        template.convertAndSend("/topic/chatroom/" + requestDto.getRoomId(), requestDto);
    }
}

이렇게 구현이 되었지만, 실제로 확인을 할 수 가 없어 별도의 프로젝트를 만들어서 시범적으로 해보기로 했다.


웹 소켓 테스트

테스트는 기능은 그대로 스프링 부트로 구현을 하고 화면은 js를 이용해서 구현을 했다.

STOMPWebSocketConfig는 기존 프로젝트와 동일하게 사용.

Controller

두가지 항목으로 테스트를 했다.

  • 컨트롤러에서 MessageMapping을 이용해서 메시지를 받고 SendTo를 이용해서 리턴값으로 메시지를 출력하는 방법
  • 컨트롤러에서 메시지만 받고 서비스에서 구현을 하여 메시지를 출력하는 방법
@RestController
@RequiredArgsConstructor
@RequestMapping("/api")
@Slf4j
public class GreetingController {

    private final ChatService chatService;

    @MessageMapping("/hello") // publish를 이용해 메시지를 받을 주소
    @SendTo("/topic/greetings") // subscribe을 이용해 메시지를 전송할 주소 
    public Greeting greeting(HelloMessage message) {
        return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
    }

    @MessageMapping("/chat/sendMessage")
    public void sendMessage(@RequestBody ChatRequestDto requestDto) {
        chatService.sendMessage(requestDto);

        log.info("roomId : " + requestDto.getRoomId() + "sender : " + requestDto.getSenderId() + " receiver : " + requestDto.getReceiverId());
        log.info("message : " + requestDto.getMessage());
    }
}

Service

메시지를 Dto로 받아 SimpMessageSendingOperations을 이용해 메시지를 정제 후 보낼 수 있다.

@Service
@RequiredArgsConstructor
public class ChatService {

    private final SimpMessageSendingOperations template;

    public void sendMessage(ChatRequestDto requestDto) {
        template.convertAndSend("/topic/chatroom/" + requestDto.getRoomId(), requestDto);
    }
}

전송에 사용된 클래스들

@NoArgsConstructor
@Getter
@AllArgsConstructor
public class Greeting {
    private String content;
}
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class HelloMessage {

    private String name;

}
@Getter
@Setter
@NoArgsConstructor
public class ChatRequestDto {

    private long roomId;
    private long senderId;
    private long receiverId;
    private String message;
}

화면 구성 HTML

<!DOCTYPE html>
<html>
<head>
    <title>Hello WebSocket</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link href="/main.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@stomp/stompjs@7.0.0/bundles/stomp.umd.min.js"></script>
    <script src="/app.js"></script>
</head>
<body>
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websocket relies on Javascript being
    enabled. Please enable
    Javascript and reload this page!</h2></noscript>
<div id="main-content" class="container">
    <div class="row">
        <div class="col-md-6">
            <form class="form-inline">
                <div class="form-group">
                    <label for="connect">WebSocket connection:</label>
                    <button id="connect" class="btn btn-default" type="submit">Connect</button>
                    <button id="disconnect" class="btn btn-default" type="submit" disabled="disabled">Disconnect
                    </button>
                </div>
            </form>
        </div>
        <div class="col-md-6">
            <form class="form-inline">
                <div class="form-group">
                    <label for="name">What is your name?</label>
                    <input type="text" id="name" class="form-control" placeholder="Your name here...">
                </div>
                <button id="send" class="btn btn-default" type="submit">greeting</button>
                <button id="send2" class="btn btn-default" type="submit">Send</button>
            </form>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <table id="conversation" class="table table-striped">
                <thead>
                <tr>
                    <th>Greetings</th>
                </tr>
                </thead>
                <tbody id="greetings">
                </tbody>
            </table>
            <table id="conversation2" class="table table-striped">
                <thead>
                <tr>
                    <th>sendMessage</th>
                </tr>
                </thead>
                <tbody id="sendMessage">
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
</html>

JS

StompJs에 웹 소켓 연결 엔드포인트를 brokerURL로 설정해서 클라이언트를 만들어주고 웹 소켓을 이용해 준다.

brokerURL을 설정해 줄 때 http가 아닌 ws로 해주어야 하고 엔드포인트를 Stomp로 설정했다면 엔드포인트 주소까지만 작성해 주고 SockJs를 이용했다면 엔드포인트 뒤에 websocker을 붙여주어야 한다.

const stompClient = new StompJs.Client({
    brokerURL: 'ws://localhost:8080/chat/websocket'
});

stompClient.onConnect = (frame) => {
    setConnected(true);
    console.log('Connected: ' + frame);
    stompClient.subscribe('/topic/greetings', (greeting) => {
        showGreeting(JSON.parse(greeting.body).content);
    });
    stompClient.subscribe('/topic/chatroom/1', (message) => {
        showMessaging(JSON.parse(message.body).message);
    });
};

stompClient.onWebSocketError = (error) => {
    console.error('Error with websocket', error);
};

stompClient.onStompError = (frame) => {
    console.error('Broker reported error: ' + frame.headers['message']);
    console.error('Additional details: ' + frame.body);
};

function setConnected(connected) {
    $("#connect").prop("disabled", connected);
    $("#disconnect").prop("disabled", !connected);
    if (connected) {
        $("#conversation").show();
    }
    else {
        $("#conversation").hide();
    }
    if (connected) {
        $("#conversation2").show();
    }
    else {
        $("#conversation2").hide();
    }
    $("#greetings").html("");
    $("#sendMessage").html("");
}

function connect() {
    stompClient.activate();
}

function disconnect() {
    stompClient.deactivate();
    setConnected(false);
    console.log("Disconnected");
}

function sendName() {
    stompClient.publish({
        destination: "/app/hello",
        body: JSON.stringify({'name': $("#name").val()})
    });
}

function sendName2() {
    stompClient.publish({
        destination: "/app/chat/sendMessage",
        body: JSON.stringify({
            'roomId': 1,
            'senderId': 5,
            'receiverId': 7,
            'message': $("#name").val()})
    });
}

function showGreeting(message) {
    $("#greetings").append("<tr><td>" + message + "</td></tr>");
}

function showMessaging(message) {
    $("#sendMessage").append("<tr><td>" + message + "</td></tr>");
}

$(function () {
    $("form").on('submit', (e) => e.preventDefault());
    $( "#connect" ).click(() => connect());
    $( "#disconnect" ).click(() => disconnect());
    $( "#send" ).click(() => sendName());
    $( "#send2" ).click(() => sendName2());
});
기본적인 원리는 stomp를 이용해서 웹 소켓을 연결한 다음 클라이언트에서 메시지를 MessageMapping 된 주소로 publish 시키고 서버에서 메시지 정보를 받아 설정된 destination으로 메시지를 다시 보내고 클라이언트에서 subscribe로 받아 메시지를 출력한다.
전반적으로 어떤 식으로 연결을 시키고 메시지를 주고받는 부분을 이해를 할 수 있었고 원리를 알고 보니 메시지 큐나 다름이 없어 보였다.
그러면 레디스나 카프카 등을 이용해서 먼가 구현을 할 수 있지 않을까도 생각이 됐다.
구현을 해보면서 다른 사람들이 한걸 보고 따라 해 보는 것도 좋지만, 역시 처음 이해하는 데는 기본 가이드만큼 좋은 곳이 없었다.

 

https://spring.io/guides/gs/messaging-stomp-websocket/

 

Getting Started | Using WebSocket to build an interactive web application

In Spring’s approach to working with STOMP messaging, STOMP messages can be routed to @Controller classes. For example, the GreetingController (from src/main/java/com/example/messagingstompwebsocket/GreetingController.java) is mapped to handle messages t

spring.io