0Pricing
GraphQL APIs with Spring Boot · 강의

Spring에 WebSockets 통합하기

구독을 위한 지속적인 클라이언트-서버 연결을 활성화하도록 Spring Boot 애플리케이션에서 WebSocket 지원을 구성합니다.

Spring에 WebSockets 통합하기은(는) CoddyKit의 무료 GraphQL APIs with Spring Boot 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 GraphQL APIs with Spring Boot 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. GraphQL APIs with Spring Boot 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

WebSockets for Real-time Data

Welcome! In this lesson, we'll integrate WebSockets with Spring Boot. This is crucial for enabling real-time features like GraphQL Subscriptions.

WebSockets provide a persistent, two-way communication channel between a client and a server over a single, long-lived TCP connection.

Why WebSockets for Subscriptions?

Unlike traditional HTTP requests (which are short-lived), GraphQL Subscriptions require a continuous connection to push data updates to clients as they happen.

WebSockets are the perfect fit because they maintain an open connection, allowing the server to send data to the client at any time without a new request.

Adding the Dependency

First, we need to add the Spring Boot WebSocket starter dependency to our project. This brings in all the necessary libraries to enable WebSocket support.

For Gradle, add this to your build.gradle:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-websocket'
}

Enabling WebSocket Message Broker

In Spring, we use annotations to enable specific functionalities. For WebSockets with a message broker, we use @EnableWebSocketMessageBroker.

This annotation enables a STOMP over WebSocket message broker, which is a powerful way to handle messaging.

Configuring WebSocket Endpoints

We need a configuration class that extends WebSocketMessageBrokerConfigurer. This class allows us to customize our WebSocket setup.

The registerStompEndpoints() method is used to define the URL endpoint clients will connect to for WebSocket communication.

Adding SockJS Fallback

When registering an endpoint, we often add .withSockJS(). SockJS is a JavaScript library that provides a WebSocket-like API.

It offers fallback options (like HTTP streaming or long polling) for browsers that don't fully support WebSockets or in environments with proxies that interfere.

Configuring the Message Broker

The configureMessageBroker() method sets up the message broker itself. This defines how messages are routed between clients and the application.

  • enableSimpleBroker("/topic"): Enables an in-memory message broker for destinations prefixed with /topic. Clients subscribe to these topics.
  • setApplicationDestinationPrefixes("/app"): Defines prefixes for messages destined for methods annotated with @MessageMapping in our application.

Complete WebSocket Configuration

Here's a minimal Spring Boot application demonstrating the WebSocket configuration. Try running it to see Spring initialize the WebSocket server!

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@SpringBootApplication
public class Main {
  public static void main(String[] args) {
    SpringApplication.run(Main.class, args);
    System.out.println("WebSocket server ready on port 8080!");
    System.out.println("Connect at ws://localhost:8080/ws-connect");
  }

  @Configuration
  @EnableWebSocketMessageBroker
  static class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

      @Override
      public void registerStompEndpoints(StompEndpointRegistry registry) {
          registry.addEndpoint("/ws-connect")
                  .withSockJS(); 
      }

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

Bridging to GraphQL Subscriptions

With this WebSocket infrastructure, our GraphQL subscription resolvers (from the previous lesson) can now publish events.

When a resolver publishes an event, Spring's message broker ensures that all clients subscribed to the relevant /topic are immediately notified via their open WebSocket connection.

Quick Check: WebSocket Config

Consider the following line from our WebSocket configuration:

config.enableSimpleBroker("/topic");

What is the primary purpose of the /topic prefix in this context?

Recap: WebSockets in Spring

Great job! You've learned how to integrate WebSockets with Spring Boot to provide a robust real-time communication layer.

  • We added the WebSocket starter dependency.
  • We used @EnableWebSocketMessageBroker and WebSocketMessageBrokerConfigurer.
  • We configured STOMP endpoints (e.g., /ws-connect with SockJS).
  • We set up a message broker with prefixes like /topic for subscriptions and /app for app-specific messages.

This setup is the foundation for delivering real-time GraphQL Subscriptions!

자주 묻는 질문

“Spring에 WebSockets 통합하기” 강의는 무료인가요?

네 — “Spring에 WebSockets 통합하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 GraphQL APIs with Spring Boot 강의 전체를 잠금 해제할 수 있습니다. GraphQL APIs with Spring Boot 강의에는 총 4개의 강의가 포함되어 있습니다.

“Spring에 WebSockets 통합하기”에서 뭘 배우나요?

구독을 위한 지속적인 클라이언트-서버 연결을 활성화하도록 Spring Boot 애플리케이션에서 WebSocket 지원을 구성합니다. 브라우저에서 직접 실행하는 실습 코드로 GraphQL APIs with Spring Boot을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

GraphQL APIs with Spring Boot을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 GraphQL APIs with Spring Boot은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“Spring에 WebSockets 통합하기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 GraphQL APIs with Spring Boot 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 GraphQL APIs with Spring Boot 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. GraphQL 구독 이해하기
  2. 실시간 업데이트 구현
  3. Spring에 WebSockets 통합하기
  4. 구독 필터링과 확장
← GraphQL APIs with Spring Boot(으)로 돌아가기