SoFunction
Updated on 2025-03-03

Three asynchronous streaming interface methods implemented in Spring

Preface

Interface timeout is a common problem in modern web development, especially when handling time-consuming operations. Traditional synchronization interfaces block request threads when processing long-term tasks, thus affecting the system's response capabilities. The Spring framework provides a variety of tools to support asynchronous streaming interfaces to effectively solve this problem. This article will explain in detail the three asynchronous streaming interface methods implemented in Spring: ResponseBodyEmitter, SseEmitter and StreamingResponseBody.

1. ResponseBodyEmitter

ResponseBodyEmitter is suitable for scenarios where content needs to be generated dynamically and sent to the client step by step, such as file upload progress, real-time logs, etc. Using ResponseBodyEmitter, you can send updates to the client step by step during task execution, making the interactive experience more vivid and natural.

Example of usage:

@GetMapping("/bodyEmitter")
public ResponseBodyEmitter handle() {
    // Create a ResponseBodyEmitter, -1 means no timeout    ResponseBodyEmitter emitter = new ResponseBodyEmitter(-1L);

    // Execute time-consuming operations asynchronously    (() -> {
        try {
            for (int i = 0; i < 10000; i++) {
                ("bodyEmitter " + i);
                // Send data                ("bodyEmitter " + i + " @ " + new Date() + "\n");
                (2000);
            }
            // Finish            ();
        } catch (Exception e) {
            // End the interface when an exception occurs            (e);
        }
    });

    return emitter;
}

In this example, by simulation responding to the result every 2 seconds, you can see that the page data is being generated dynamically. The timeout time of ResponseBodyEmitter can be set to 0 or -1, indicating that the connection will not time out. If not set, the connection will automatically disconnect after the default timeout is reached.

2. SseEmitter

SseEmitter is a subclass of ResponseBodyEmitter, which is mainly used for servers to push real-time data to clients, such as real-time message push, status update and other scenarios. Server-Sent Events (SSE) technology opens a one-way channel between the server and the client. The server responds to no longer one-time data packets, but text/event-stream type data flow information.

Example of usage:

@GetMapping("/subSseEmitter/{userId}")
public SseEmitter sseEmitter(@PathVariable String userId) {
    ("sseEmitter: {}", userId);
    SseEmitter emitterTmp = new SseEmitter(-1L);
    // Persist the SseEmitter object so that the corresponding sender will be directly retrieved when the message is generated    EMITTER_MAP.put(userId, emitterTmp);

    (() -> {
        try {
            // Simulate sending data             event = ()
                .data("sseEmitter" + userId + " @ " + ());
            (event);
            // More sending logic can be added here        } catch (Exception e) {
            (e);
        }
    });

    return emitterTmp;
}

On the client, you can establish a connection through the EventSource object and listen to the message event to receive data sent by the server.

3. StreamingResponseBody

StreamingResponseBody is used to output the response body as a stream, suitable for scenarios where large amounts of data are required to output and are not suitable for use with ResponseBodyEmitter or SseEmitter.

Example of usage:

@GetMapping("/streaming")
public StreamingResponseBody streaming() {
    return outputStream -> {
        // Execute time-consuming operations asynchronously        (() -> {
            try {
                for (int i = 0; i < 10000; i++) {
                    String data = "Streaming data " + i + "\n";
                    (());
                    ();
                    (1000);
                }
                ();
            } catch (Exception e) {
                // Handle exceptions            }
        });
    };
}

In this example, data is gradually written into the response output stream by performing time-consuming operations asynchronously. StreamingResponseBody is suitable for scenarios where data streams need to be continuously output, such as video streams, file downloads, etc.

Summarize

By using ResponseBodyEmitter, SseEmitter and StreamingResponseBody, the Spring framework provides powerful asynchronous streaming interface support, effectively solving the problem of interface timeout. These methods allow the gradual sending of updates to the client during task execution, improving the system's responsiveness and user experience. Depending on the specific application scenario, you can choose the appropriate tool to implement the asynchronous streaming interface.

The above is the detailed content of the three asynchronous streaming interface methods implemented in Spring. For more information about Spring's asynchronous streaming interface methods, please pay attention to my other related articles!