본문 바로가기

Study Information Technology

실시간 분석 대시보드 구축 Spring Boot와 WebSocket 활용

728x90
반응형

실시간 분석 대시보드 구축: Spring Boot와 WebSocket 활용

Overview

실시간 분석 대시보드를 구축하는 것은 데이터 변화를 즉시 클라이언트 측에 반영하여 사용자 경험을 개선하는 데 매우 유용합니다. Spring Boot와 WebSocket을 활용하면, 서버와 클라이언트 간의 효율적인 양방향 통신을 통해 데이터를 실시간으로 전송할 수 있습니다. 이번 글에서는 Spring Boot를 사용하여 WebSocket 기반의 실시간 분석 대시보드를 구축하는 과정을 단계별로 자세히 설명하겠습니다.


1. 개발 환경 설정

우선, 필요한 개발 환경을 설정해야 합니다. 아래는 Spring Boot와 WebSocket을 활용하기 위한 기본 설정입니다.

1.1. Spring Boot 프로젝트 생성

Spring Initializr(https://start.spring.io/)를 이용해 기본 프로젝트를 생성합니다. 필요한 의존성으로는 Spring Web, Spring WebSocket, Spring Data JPA, H2 Database를 추가합니다.

1.2. Maven 의존성

프로젝트의 pom.xml 파일에 아래와 같이 의존성을 추가합니다:

<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  <dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
  </dependency>
</dependencies>

2. WebSocket 설정

WebSocket을 설정하여 클라이언트와 서버 간의 통신을 구현합니다.

2.1. WebSocket 구성 클래스

다음은 WebSocket 설정을 위한 Java 클래스를 작성하는 방법입니다.

import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}

@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
}

위 코드에서 /ws 엔드포인트를 통해 WebSocket 연결을 설정합니다. 또한, /topic을 통해 구독하는 메시지 브로커를 설정합니다.

3. 데이터 모델 및 서비스

실시간으로 업데이트할 데이터 모델을 정의하고, 해당 데이터를 처리할 서비스를 구현합니다.

3.1. 데이터 모델

예를 들어, UserActivity라는 데이터를 기록할 모델을 다음과 같이 생성합니다.

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class UserActivity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String username;
private String activity;

// Getters and Setters
}

3.2. 데이터 저장 서비스

UserActivityService 클래스를 작성하여 데이터를 저장하고 클라이언트에게 전송할 준비를 합니다.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

@Service
public class UserActivityService {
@Autowired
private SimpMessagingTemplate messagingTemplate;

public void logActivity(UserActivity activity) {
// 데이터 저장 로직 (예: JPA Repository 사용)
messagingTemplate.convertAndSend("/topic/userActivities", activity);
}
}

4. 컨트롤러 구현

클라이언트 요청을 처리하는 RESTful API와 WebSocket 메시지를 처리하는 컨트롤러를 구현합니다.

4.1. REST API

다음은 사용자 활동을 기록하는 REST API입니다.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/activities")
public class UserActivityController {
@Autowired
private UserActivityService activityService;

@PostMapping
public void createActivity(@RequestBody UserActivity activity) {
activityService.logActivity(activity);
}
}

5. 클라이언트 구현

이제 HTML과 JavaScript를 사용하여 클라이언트를 구현합니다. WebSocket을 통해 데이터를 받아오고, 실시간으로 대시보드에 표시하는 기능을 추가합니다.

5.1. HTML 파일

아래는 기본적인 HTML 구조입니다.

<!DOCTYPE html>
<html>
  <head>
    <title>Real-time Dashboard</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.5.0/sockjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
  </head>
  <body>
    <h1>Real-time User Activities</h1>
    <div id="activities"></div>

    <script>
      const socket = new SockJS('/ws');
      const stompClient = Stomp.over(socket);

      stompClient.connect({}, function (frame) {
        stompClient.subscribe('/topic/userActivities', function (activity) {
          const activityElement = document.createElement('div');
          activityElement.innerText = JSON.parse(activity.body).username + ': ' + JSON.parse(activity.body).activity;
          document.getElementById('activities').appendChild(activityElement);
        });
      });
    </script>
  </body>
</html>

6. 에러 처리 및 디버깅

개발 중에 발생할 수 있는 에러 메시지와 그 해결 방법을 살펴보겠습니다.

6.1. Common Errors

  • Error 404: WebSocket 엔드포인트를 찾을 수 없을 때 발생합니다. 이 경우, 엔드포인트가 올바르게 설정되었는지 확인해야 합니다.
  • Error 401: 인증되지 않은 사용자가 WebSocket에 연결하려 할 때 발생합니다. Spring Security 설정을 추가해야 할 수 있습니다.

이와 같은 에러가 발생하면, 각 설정과 로그를 확인하여 원인을 파악하고 수정해야 합니다.

7. 결론

이제 Spring Boot와 WebSocket을 활용한 실시간 분석 대시보드를 구축하는 방법을 알아보았습니다. 이 방법을 통해 데이터가 업데이트될 때마다 클라이언트에게 즉시 전달할 수 있는 시스템을 구현할 수 있습니다. 데이터의 흐름을 이해하고, 이를 기반으로 실시간 사용자 경험을 향상시키는 대시보드를 만들 수 있습니다.

참고문서

728x90
반응형