WebSockets & Real-Time Systems with Spring · 课时

监控 WebSocket 连接

实施监控解决方案,跟踪活动连接数、消息速率和服务器运行状况。

第 2 / 4 课11 个步骤

监控 WebSocket 连接 是 CoddyKit 上的免费 WebSockets & Real-Time Systems with Spring 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 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!

免费开始

用 AI 导师学习 WebSockets & Real-Time Systems with Spring — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
12
课程
48

常见问题解答

「监控 WebSocket 连接」课时是免费的吗?

是的 — 「监控 WebSocket 连接」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 WebSockets & Real-Time Systems with Spring 课程的其余内容,请升级到 CoddyKit PRO。 WebSockets & Real-Time Systems with Spring 课程共包含 4 节课。

「监控 WebSocket 连接」这节课中我会学到什么?

实施监控解决方案,跟踪活动连接数、消息速率和服务器运行状况。 你通过在浏览器中直接运行的动手代码来练习 WebSockets & Real-Time Systems with Spring,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 WebSockets & Real-Time Systems with Spring 需要有经验吗?

无需任何先前经验。CoddyKit 上的 WebSockets & Real-Time Systems with Spring 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 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