0Pricing
GraphQL APIs with Spring Boot · Pelajaran

Mengintegrasikan WebSockets dengan Spring

Konfigurasikan dukungan WebSocket dalam aplikasi Spring Boot untuk mengaktifkan koneksi klien-server persisten bagi subscription.

Mengintegrasikan WebSockets dengan Spring adalah pelajaran GraphQL APIs with Spring Boot gratis di CoddyKit. Ini adalah pelajaran 3 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar GraphQL APIs with Spring Boot, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus GraphQL APIs with Spring Boot mencakup 4 pelajaran total.

Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.

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!

Pertanyaan yang Sering Diajukan

Apakah pelajaran “Mengintegrasikan WebSockets dengan Spring” gratis?

Ya — teks lengkap “Mengintegrasikan WebSockets dengan Spring” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus GraphQL APIs with Spring Boot, upgrade ke CoddyKit PRO. Kursus GraphQL APIs with Spring Boot mencakup 4 pelajaran total.

Apa yang akan aku pelajari di “Mengintegrasikan WebSockets dengan Spring”?

Konfigurasikan dukungan WebSocket dalam aplikasi Spring Boot untuk mengaktifkan koneksi klien-server persisten bagi subscription. Kamu berlatih GraphQL APIs with Spring Boot dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.

Apakah aku perlu pengalaman untuk memulai GraphQL APIs with Spring Boot?

Tidak diperlukan pengalaman sebelumnya. GraphQL APIs with Spring Boot di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 3 dari 4.

Berapa lama pelajaran “Mengintegrasikan WebSockets dengan Spring” memakan waktu?

Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.

Bisakah aku menulis dan menjalankan kode dalam pelajaran GraphQL APIs with Spring Boot ini?

Ya. Setiap pelajaran GraphQL APIs with Spring Boot menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.

Semua pelajaran dalam kursus ini

  1. Memahami Subscription GraphQL
  2. Menerapkan Pembaruan Waktu Nyata
  3. Mengintegrasikan WebSockets dengan Spring
  4. Pemfilteran dan Penskalaan Langganan
← Kembali ke GraphQL APIs with Spring Boot