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

การตรวจติดตามการเชื่อมต่อ WebSocket

นำโซลูชันตรวจติดตามไปใช้เพื่อติดตามการเชื่อมต่อที่ใช้งานอยู่ อัตราการส่งข้อความ และสถานะของเซิร์ฟเวอร์

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

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

Why Monitor WebSockets?

Real-time applications, powered by WebSockets, need constant attention to ensure smooth operation. Unlike traditional HTTP, WebSockets maintain persistent connections, making their health critical.

Monitoring helps us understand performance, identify bottlenecks, and react quickly to issues before users are affected. It's key for reliable real-time experiences.

Essential WebSocket Metrics

When monitoring WebSockets, focus on these key areas:

  • Active Connections: How many clients are currently connected?
  • Message Rates: How many messages are sent/received per second?
  • Error Rates: How often do connections fail or messages encounter errors?
  • Latency: How quickly are messages processed and delivered?

Tracking these gives you a clear picture of your application's health.

Basic Monitoring with Actuator

Spring Boot Actuator provides production-ready features to monitor and manage your application. It exposes various endpoints that give insights into your app's health, metrics, and environment.

While not specific to WebSockets, Actuator can show general JVM metrics, HTTP request metrics, and overall application health, which are foundational for any monitoring setup.

Actuator's Metrics Endpoint

To get started, add the Actuator dependency to your pom.xml. Then, you can access endpoints like /actuator/health or /actuator/metrics.

The /actuator/metrics endpoint lists available metrics, including some related to thread pools or network activity that might indirectly reflect WebSocket load.

<!-- pom.xml snippet -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Micrometer for Custom Metrics

For WebSocket-specific metrics, we'll use Micrometer, Spring Boot's metrics facade. It allows you to instrument your code with custom counters, gauges, timers, and more, which can then be exported to various monitoring systems.

Micrometer provides a unified API, letting you choose your monitoring backend (like Prometheus, Grafana, etc.) without changing your code.

Counting Live WebSocket Sessions

To track active WebSocket connections, we can use an AtomicInteger to count sessions. Micrometer's Gauge can then expose this value.

A Gauge is perfect for values that fluctuate, like the number of currently connected clients. In a real app, you'd update this counter on connect/disconnect events.

import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.util.concurrent.atomic.AtomicInteger;

public class SessionCounterDemo {
    private final AtomicInteger activeSessions = new AtomicInteger(0);
    private final MeterRegistry meterRegistry;

    public SessionCounterDemo(MeterRegistry registry) {
        this.meterRegistry = registry;
        Gauge.builder("websocket.active.sessions", activeSessions, AtomicInteger::get)
             .description("Number of active WebSocket sessions")
             .register(meterRegistry);
    }

    public void connect() {
        activeSessions.incrementAndGet();
    }

    public void disconnect() {
        activeSessions.decrementAndGet();
    }

    public static void main(String[] args) {
        MeterRegistry registry = new SimpleMeterRegistry();
        SessionCounterDemo demo = new SessionCounterDemo(registry);

        System.out.println("Initial sessions: " + demo.activeSessions.get());
        demo.connect();
        demo.connect();
        System.out.println("After 2 connects: " + demo.activeSessions.get());
        demo.disconnect();
        System.out.println("After 1 disconnect: " + demo.activeSessions.get());
    }
}

Tracking Message Rates

Besides connections, tracking message rates is crucial. We can use a Micrometer Counter to increment each time a message is sent or received.

A Counter is a single-value metric that only increases. It's perfect for counting events like messages processed, requests handled, or errors occurred.

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;

public class MessageCounterDemo {
    private final Counter messagesReceived;

    public MessageCounterDemo(MeterRegistry registry) {
        this.messagesReceived = Counter.builder("websocket.messages.received")
                                        .description("Number of WebSocket messages received")
                                        .register(registry);
    }

    public void onMessageReceived(String message) {
        messagesReceived.increment();
        System.out.println("Received message: " + message);
    }

    public static void main(String[] args) {
        MeterRegistry registry = new SimpleMeterRegistry();
        MessageCounterDemo demo = new MessageCounterDemo(registry);

        System.out.println("Initial messages: " + demo.messagesReceived.count());
        demo.onMessageReceived("Hello");
        demo.onMessageReceived("World");
        System.out.println("Total messages: " + demo.messagesReceived.count());
    }
}

Capturing WebSocket Errors

Errors can occur at various stages: connection handshakes, message parsing, or business logic. It's vital to track these to maintain application stability.

You can use a Counter for specific error types, perhaps with tags to differentiate between connection errors, message format errors, or server processing errors.

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;

public class ErrorCounterDemo {
    private final Counter connectionErrors;
    private final Counter messageProcessingErrors;

    public ErrorCounterDemo(MeterRegistry registry) {
        this.connectionErrors = Counter.builder("websocket.errors.total")
                                       .tag("type", "connection")
                                       .description("Total connection errors")
                                       .register(registry);
        this.messageProcessingErrors = Counter.builder("websocket.errors.total")
                                              .tag("type", "message_processing")
                                              .description("Total message processing errors")
                                              .register(registry);
    }

    public void simulateConnectionError() {
        connectionErrors.increment();
        System.out.println("Connection error occurred.");
    }

    public void simulateMessageProcessingError() {
        messageProcessingErrors.increment();
        System.out.println("Message processing error occurred.");
    }

    public static void main(String[] args) {
        MeterRegistry registry = new SimpleMeterRegistry();
        ErrorCounterDemo demo = new ErrorCounterDemo(registry);

        System.out.println("Initial connection errors: " + demo.connectionErrors.count());
        demo.simulateConnectionError();
        System.out.println("Connection errors after one: " + demo.connectionErrors.count());
        demo.simulateMessageProcessingError();
        System.out.println("Message processing errors: " + demo.messageProcessingErrors.count());
    }
}

Exporting Metrics to Dashboards

Once you've instrumented your application with Micrometer, these metrics can be exported to various monitoring systems like Prometheus, Grafana, Datadog, or New Relic.

These systems then allow you to build powerful dashboards to visualize your WebSocket metrics in real-time. This helps you spot trends, set alerts, and troubleshoot issues effectively.

Micrometer Metrics Check

You want to track the number of currently active users in a chat application. Which Micrometer metric type is best suited for this purpose?

Monitoring Recap

Great job! You've learned the importance of monitoring WebSocket applications and how to implement it.

  • We explored key WebSocket metrics like active connections and message rates.
  • You saw how Spring Boot Actuator offers basic health checks.
  • We used Micrometer to create custom Gauge and Counter metrics for WebSocket sessions and messages.

Next, dive into specific tools like Prometheus and Grafana to visualize these metrics and build robust dashboards!

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

บทเรียน “การตรวจติดตามการเชื่อมต่อ WebSocket” ฟรีหรือไม่

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

คุณจะเรียนรู้อะไรในบทเรียน “การตรวจติดตามการเชื่อมต่อ WebSocket”

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

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

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

บทเรียน “การตรวจติดตามการเชื่อมต่อ 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