SoFunction
Updated on 2025-04-25

Spring Boot Integrates Advanced Practice of SSE (Server-Sent Events)

1. Brief description

SSE (Server-Sent Events) is a kind of HTTP protocol-basedOne-way communication mechanism, allowing the server to continuously send real-time updates to the browser. Unlike WebSocket, SSE is simpler and can be used to use HTTP/1.1 protocol without additional protocol upgrades.

Features of SSE:

  • One-way communication: The server pushes data to the client, and the client cannot send messages to the server.
  • Simple and easy to use: based on HTTP protocol, no complicated configuration required.
  • Browser support: Most modern browsers have built-in support (such as Chrome, Edge, Firefox, etc.).

2. SSE implementation in Spring Boot

2.1 Add dependencies

SSE does not require additional dependencies, Spring Boot comes with SSE support. Just create a Spring Boot project.

<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2.2 Implementing the backend interface

useMediaType.TEXT_EVENT_STREAM_VALUESSE can be enabled as the return type. The following code is a simple implementation.

package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@RestController
public class SseController {
    @GetMapping(value = "/sse/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Stream&lt;String&gt; stream() {
        // Simulate data flow        return (() -&gt; "Current time:" + ())
                     .limit(10); // Limit 10 messages    }
}

2.3 Configure timeout (optional)

By default, Spring Boot's response timeout. Can beAdjusted timeout time:

=30s
-timeout=30000

2.4 Front-end implementation

SSE passes on the front endEventSourceObject implementation. Here is a simple front-end example:

&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;title&gt;SSE Example&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;h1&gt;Real-time message&lt;/h1&gt;
    &lt;div &gt;&lt;/div&gt;
    &lt;script&gt;
        const eventSource = new EventSource('/sse/stream');
         = function(event) {
            const messagesDiv = ('messages');
            const newMessage = ('p');
             = ;
            (newMessage);
        };
         = function() {
            ('The SSE connection error is occuring, trying to reconnect...');
            ();
        };
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

3. Advanced Practice

Use Spring Scheduler to push data. In actual scenarios, it may be necessary to push data to the client regularly. For example, the monitoring system is updated regularly.

package ;
import ;
import ;
import ;
import ;
import ;
@Service
public class SsePushService {
    private final CopyOnWriteArrayList<SseEmitter> emitters = new CopyOnWriteArrayList<>();
    public SseEmitter subscribe() {
        SseEmitter emitter = new SseEmitter(30_000L);
        (emitter);
        (() -> (emitter));
        (() -> (emitter));
        return emitter;
    }
    public void pushMessage(String message) {
        for (SseEmitter emitter : emitters) {
            try {
                (message, MediaType.TEXT_PLAIN);
            } catch (IOException e) {
                (emitter);
            }
        }
    }
}

Create a controller subscription and push messages:

package ;
import ;
import ;
import ;
@RestController
public class SsePushController {
    private final SsePushService ssePushService;
    public SsePushController(SsePushService ssePushService) {
         = ssePushService;
    }
    @GetMapping("/sse/subscribe")
    public SseEmitter subscribe() {
        return ();
    }
    @GetMapping("/sse/push")
    public void pushMessage() {
        ("Current time:" + ());
    }
}

Notes:

  • Browser Compatibility: SSE does not support IE, but modern browsers support it well.
  • Connection disconnection processing: can be passedEventSourceofonerrorEvent reconnect.
  • Performance issues: When a large number of subscribers, you need to consider using distributed message queue optimization (such as Kafka).
  • Timeout time: The default timeout is 30 seconds, and it needs to be adjusted according to actual needs.

4. Applicable scenarios

  • Real-time notification: such as alarm push from the monitoring system.
  • Real-time updates: such as stock market and sports scores.
  • Message flow: such as system logs, task progress.

This is the end of this article about Spring Boot Integration SSE (Server-Sent Events). For more related Spring Boot Integration SSE content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!