Member-only story

Spring Boot | Server-sent events (SSE)

Egor Voronianskii
3 min readJan 30, 2024
Simple example of SSE interactions

I will show you how to use server-sent events in your Spring Boot application in this article.

Introduction

Before going into details, let’s talk about theory. The SSE is not a new fancy approach; it has been here since 2004. The first browser that started to support SSE was Opera in 2006. Now, all modern browsers support this technology.
How is SSE different from the hit-and-get approach from the REST?
In REST API, we hit some methods and get back some responses. In the server sents events, the consumer of REST API subscribes to events from the server.

The server-sent events are text data streams encoded in UTF-8. The data format is key-value pairs — the server-sent events to offer only uni-directional communication. Meanwhile, WebSockets offer bi-directional (full duplex) communication.

Implementation

I will use Spring Boot WebFlux in this article, but SSE can also be implemented with Spring MVC.
Let’s start with a simple endpoint that will return the current traffic situation on the road every two seconds. Here is the implementation of the traffic service.

package io.vrnsky.serversenteventsdemo;

import org.springframework.stereotype.Service;

import…

--

--

Egor Voronianskii
Egor Voronianskii

Written by Egor Voronianskii

I am a Software Engineer, JVM enthusiast, cat - lover, part-time surfer.

No responses yet