SoFunction
Updated on 2025-03-09

Springboot Project Practice for Implementing Server-Sent Events

existSpring Boot, returntext/event-streamTypes of responses are usually used to implementServer-Sent Events (SSE), this method allows the server to push real-time updates to the browser. Client passEventSourceThe API listens for and receives these events. Spring Boot can be used@RestControllerandSseEmitterTo implement this function.

Step 1: Create SSE Controller and return text/event-stream

We can pass@GetMappingTo create an API, returntext/event-streamTypes of data. This data will be a continuous stream and the browser will receive it in real time.

Example: Return a response of type text/event-stream through Spring Boot

  • Controller: Define a return in Spring Boottext/event-streamTypes of API interface.
  • useSseEmitterSseEmitteris a class provided by Spring to handle Server-Sent Events streams. We can use it to push data to the client asynchronously.

Example 1: Simple SSE implementation

In this example, we will create a simple Spring Boot controller that will return a live stream of events (SSE).

import ;
import ;
import ;

@RestController
public class SseController {

    /**
      * This interface will return a continuous event stream, and the browser will receive it through EventSource
      */
    @GetMapping("/sse")
    public SseEmitter handleSse() {
        SseEmitter emitter = new SseEmitter();

        // Start a new thread to simulate periodic push events        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    // Send data to the client                    ("data: Event " + i + "\n\n");
                    (1000); // Send once per second                }
                (); // After sending, the mark event stream is completed            } catch (Exception e) {
                (e); // If an exception occurs, the mark event leaks out            }
        }).start();

        return emitter; // Returns the SseEmitter instance, which handles asynchronous streaming data    }
}

illustrate:

  • SseEmitterUsed to handle SSE connections. We will pass the data()Send to the client.
  • Event passeddata: <message>Send format to the client, note that each message ends with two newline characters (\n\n)。
  • (1000)Used to simulate sending one event per second. If you need to send events regularly, it can be achieved through a similar mechanism.
  • Finally, by()Mark the end of the event stream. If an error occurs, use()

Step 2: Front-end receives SSE events

On the front end, use JavaScriptEventSourceAPI receives events pushed by the server. This API will maintain a connection to the server, and the browser will automatically handle it once new events are present.

&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;title&gt;Server-Sent Events Example&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;h1&gt;Server-Sent Events Example&lt;/h1&gt;
&lt;div &gt;&lt;/div&gt;

&lt;script&gt;
    // Create an EventSource object and connect to the /sse interface    const eventSource = new EventSource("/sse");

    // Process the event whenever data is received     = function(event) {
        const messagesDiv = ('messages');
        const message = ('p');
         = ;
        (message);
    };

    // Error handling     = function(error) {
        ("EventSource failed:", error);
    };
&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;

Step 3: Configure Spring Boot to enable asynchronous support

SSE usually requires asynchronous processing, so it is important to enable asynchronous support in Spring Boot. Can be passed@EnableAsyncTo enable asynchronous support.

Enable asynchronous support

import ;
import ;

@Configuration
@EnableAsync
public class AsyncConfig {
}

Step 4: Timely push data (optional)

If you want to push events regularly (for example, push a message every certain time), you can use Spring's@ScheduledAnnotations to arrange timing tasks.

Example: Timed event sending

import ;
import ;

@Controller
public class ScheduledSseController {

    private final SseEmitter emitter = new SseEmitter();

    @Scheduled(fixedRate = 5000)  // Send an event every 5 seconds    public void sendScheduledEvent() {
        try {
            ("data: Scheduled Event at " + () + "\n\n");
        } catch (IOException e) {
            (e);
        }
    }
}

In the example above,@Scheduled(fixedRate = 5000)Events will be sent regularly every 5 seconds.

Step 5: Handle multi-client connections

If you need to manage multiple client connections, you canSseEmitterThe instance is stored in a list and events are sent for each connection. Whenever there is a new event, you can send events to all connected clients by traversing these connections.

import ;
import ;
import ;

import ;
import ;
import ;

@Controller
public class MultiClientSseController {

    private final List&lt;SseEmitter&gt; emitters = new CopyOnWriteArrayList&lt;&gt;();

    @GetMapping("/sse")
    public SseEmitter handleSse() {
        SseEmitter emitter = new SseEmitter();
        (emitter);

        // Send data in a new thread        new Thread(() -&gt; {
            try {
                for (int i = 0; i &lt; 10; i++) {
                    for (SseEmitter e : emitters) {
                        ("data: Event " + i + "\n\n");
                    }
                    (1000); // Send once per second                }
            } catch (Exception e) {
                (SseEmitter::completeWithError);
            }
        }).start();

        return emitter;
    }
}

Summarize

  • returntext/event-stream: Used in Spring Boot ControllerSseEmitterOr directly pass@GetMappingReturn streaming data.
  • Front-end reception event: Using the browserEventSourceAPI to receive event streams.
  • Timed events: Can be used@ScheduledTo push events regularly, or push dynamic data through background threads.
  • Multi-client support: Can manage multipleSseEmitterinstance, push events for each client.

This method is very suitable for real-time data push, such as stock market updates, social media notifications, real-time messages and other application scenarios.

This is the article about Springboot implementation of Server-Sent Events project practice. For more related Springboot implementation of Server-Sent Events, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!