Spring 5, which will release later this year, will support building asynchronous and Reactive applications.

To know more about the features in Spring 5 and Reactive Programming, you can refer to this article.

I’ll highly suggest you to do that.

Spring 5 will make it easier to implement Server-Sent Events (SSE).

We’ll see with the help of a simple stock market simulation how to implement SSE.

2. Server-Sent Events (SSE)

SSE is a web technology where a browser receives updates from a server via HTTP connection.

It is better than polling because polling has a lot of HTTP overhead.

Unlike WebSockets, it is unidirectional (server to browser).

SSEs are sent over traditional HTTP, hence they don’t require any special implementation on the server.

3. Dependencies

We’ll use Gradle to build our project. I recommend using Spring Initializr for bootstrapping your project.

We’ll use:

Not all the Spring libraries have a stable release yet.

4. Stock Market Example

In this example, we’ll simulate stock market transactions and notify the client about them.

The steps involved are:

Let’s have a look at the Stock class.

We’ll initialize some random Stocks at the start of the application.

Let’s have a look at the StockTransaction class.

5. Reactive SSE

We’ll create a service which returns a Flux of StockTransactions.

We are creating a Flux which generates a long value every second. We are then updating the price of every stock.

We are creating another Flux which creates a StockTransaction.

The Flux.zip method is taking both these Flux and combining them.

They’ll be combined in a strict sequence (when both Flux have emitted their nth item).

We are then returning the second Flux.

Hence, the resulting Flux will emit a StockTransaction after every second.

5. Web API

We’ll create an endpoint GET /stock/transaction which will continuously fetch details of the latest transactions happening.

MediaType.APPLICATION_STREAM_JSON_VALUE signifies that the server will send SSE.

This API will return a response with the header Content-Type: application/stream+json.

The cURL commands for testing this is
curl -v http://localhost:8080/stock/transaction.

The output obtained will look like this

6. Conclusion

I have tried explaining, with a simple example, how to send SSE using Spring Boot.

You can read more about:

You can find the complete example on Github.