0Pricing
WebSockets & Real-Time Systems with Spring · บทเรียน

การปรับแต่งการตั้งค่า Spring WebSocket

ปรับการตั้งค่า Spring WebSocket ให้เหมาะสมกับสภาพแวดล้อมที่มีปริมาณงานสูงและความหน่วงต่ำ

การปรับแต่งการตั้งค่า Spring WebSocket เป็นบทเรียน WebSockets & Real-Time Systems with Spring ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน WebSockets & Real-Time Systems with Spring และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส WebSockets & Real-Time Systems with Spring มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why Tune WebSockets?

Your real-time applications need to be fast and reliable! Spring WebSockets come with sensible defaults, but for high-traffic or low-latency scenarios, you'll need to fine-tune them.

This lesson will show you how to optimize your Spring WebSocket configurations for peak performance and improved user experience.

Throughput & Latency Goals

When we talk about performance tuning, we often focus on two key metrics:

  • Throughput: How many messages or operations can your system handle per second? Higher is usually better.
  • Latency: How long does it take for a message to travel from sender to receiver? Lower is always better.

Optimizing these ensures a smooth and responsive real-time application.

WebSocket Buffer Sizes

Spring's underlying WebSocket container has limits on the size of individual messages. If your application sends or receives very large messages, the defaults might be too restrictive, causing messages to be rejected.

  • Text Message Buffer: For text-based messages (e.g., JSON strings).
  • Binary Message Buffer: For binary data (e.g., images, files).

You can increase these limits to accommodate larger payloads.

Example: Setting Buffer Limits

You can configure the maximum text and binary message buffer sizes by defining a ServletServerContainerFactoryBean bean in your configuration. This ensures the underlying WebSocket container can handle larger messages.

import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;
import org.springframework.context.annotation.Bean;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        // Handlers would be registered here, e.g., registry.addHandler(myHandler(), "/my-websocket");
    }

    @Bean
    public ServletServerContainerFactoryBean createWebSocketContainer() {
        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
        container.setMaxTextMessageBufferSize(16384); // Double the default (8192)
        container.setMaxBinaryMessageBufferSize(16384); // Double the default
        System.out.println("WebSocket container buffer sizes set to 16KB.");
        return container;
    }

    public static void main(String[] args) {
        // This config class is loaded by Spring Boot, not run directly.
        // We simulate its effect for demonstration.
        System.out.println("To apply these settings, run a Spring Boot app with this config.");
    }
}

STOMP Frame Size Limits

If you're using STOMP over WebSockets for structured messaging, there are additional buffer limits that control the maximum size of STOMP frames. These are distinct from the raw WebSocket buffer sizes.

  • Send Buffer Limit: Max size for outgoing STOMP frames from the server.
  • Receive Buffer Limit: Max size for incoming STOMP frames to the server.

These limits are configured on the STOMP endpoint itself.

Example: STOMP Buffer Tuning

You can set STOMP-specific buffer limits directly on the endpoint registry. This ensures that large STOMP messages (which contain headers and body) don't exceed your desired limits, preventing potential memory issues or denial-of-service attacks.

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;

@Configuration
@EnableWebSocketMessageBroker
public class StompWebSocketConfig implements WebSocketMessageBrokerConfigurer {

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

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws")
                .setAllowedOrigins("*")
                .setSendBufferLimit(512 * 1024) // 512KB for outgoing STOMP frames
                .setReceiveBufferLimit(512 * 1024); // 512KB for incoming STOMP frames
        System.out.println("STOMP endpoint buffer limits set to 512KB.");
    }

    public static void main(String[] args) {
        System.out.println("STOMP WebSocket config with buffer limits prepared.");
    }
}

Keeping Connections Alive (Heartbeats)

WebSocket connections can sometimes become 'stale' without activity, especially when passing through network proxies or load balancers. STOMP heartbeats are crucial for maintaining connection health.

  • They send small 'ping' messages at regular intervals.
  • This prevents idle connections from being silently closed.
  • They help detect unresponsive clients or servers quickly.

You configure both the server's send and receive heartbeat intervals.

Example: Setting STOMP Heartbeats

To enable and configure heartbeats, use the setHeartbeatValue method on your message broker configuration. The array represents [server-send-interval, server-receive-interval] in milliseconds.

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;

@Configuration
@EnableWebSocketMessageBroker
public class StompHeartbeatConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic")
              .setHeartbeatValue(new long[]{10000, 10000}); // Server sends every 10s, expects client every 10s
        config.setApplicationDestinationPrefixes("/app");
        System.out.println("STOMP broker heartbeat set to 10 seconds.");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").setAllowedOrigins("*");
    }

    public static void main(String[] args) {
        System.out.println("STOMP WebSocket config with heartbeat values prepared.");
    }
}

Message Handler Thread Pool

When your Spring server receives STOMP messages, they are processed by a thread pool. By default, Spring provides a basic one, but for high-load applications, you'll gain significant performance by configuring a dedicated ThreadPoolTaskExecutor.

  • Core Pool Size: The minimum number of threads always running.
  • Max Pool Size: The maximum number of threads allowed in the pool.
  • Queue Capacity: How many tasks can wait if all threads are busy.

Properly sizing this executor is vital for handling concurrent messages efficiently.

Example: Custom Task Executor

You can define a custom ThreadPoolTaskExecutor and assign it to the client inbound channel. This gives you fine-grained control over how many concurrent messages your application can process.

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.messaging.simp.config.ChannelRegistration;

@Configuration
@EnableWebSocketMessageBroker
public class CustomExecutorConfig implements WebSocketMessageBrokerConfigurer {

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

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").setAllowedOrigins("*");
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.taskExecutor(clientInboundExecutor());
        System.out.println("Custom client inbound task executor configured.");
    }

    @Bean
    public ThreadPoolTaskExecutor clientInboundExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(8); // Start with 8 threads
        executor.setMaxPoolSize(16);  // Allow up to 16 threads
        executor.setQueueCapacity(512); // Queue up to 512 tasks
        executor.setThreadNamePrefix("StompInbound-");
        executor.initialize();
        return executor;
    }

    public static void main(String[] args) {
        System.out.println("STOMP WebSocket config with custom task executor prepared.");
    }
}

Quick Check: Tuning Options

Which of the following Spring WebSocket configuration settings can directly impact the performance (throughput and/or latency) of your real-time application?

Recap: Optimize Your WebSockets

Great job! You've learned how to fine-tune your Spring WebSocket applications for better performance.

  • We adjusted WebSocket buffer sizes for larger messages.
  • Configured STOMP frame limits for structured data.
  • Set up heartbeats to maintain connection health.
  • Customized the message handling thread pool for concurrency.

Applying these settings is crucial for building robust, scalable, and high-performance real-time systems!

คำถามที่พบบ่อย

บทเรียน “การปรับแต่งการตั้งค่า Spring WebSocket” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การปรับแต่งการตั้งค่า Spring WebSocket” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส WebSockets & Real-Time Systems with Spring ให้อัปเกรดเป็น CoddyKit PRO คอร์ส WebSockets & Real-Time Systems with Spring มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การปรับแต่งการตั้งค่า Spring WebSocket”

ปรับการตั้งค่า Spring WebSocket ให้เหมาะสมกับสภาพแวดล้อมที่มีปริมาณงานสูงและความหน่วงต่ำ คุณปฏิบัติ WebSockets & Real-Time Systems with Spring ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน WebSockets & Real-Time Systems with Spring หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน WebSockets & Real-Time Systems with Spring บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การปรับแต่งการตั้งค่า Spring WebSocket” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน WebSockets & Real-Time Systems with Spring นี้ได้ไหม

ได้ บทเรียน WebSockets & Real-Time Systems with Spring ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การวัดประสิทธิภาพ WebSocket
  2. การตรวจติดตามการเชื่อมต่อ WebSocket
  3. การปรับแต่งการตั้งค่า Spring WebSocket
  4. การลดแบนด์วิดท์ด้วยการบีบอัดข้อความ
← กลับไปที่ WebSockets & Real-Time Systems with Spring