Languages
[Edit]
EN

Spring Boot 3 - server-sent events example using Spring MVC

10 points
Created by:
Selina-Miranda
737

In this article, we would like to show how to use server-sent events with Spring MVC under Spring Boot 3.

In the example project we used HTTP/2 protocol for better performance.

 

Warning from MDN:

When not used over HTTP/2, SSE suffers from a limitation to the maximum number of open connections, which can be specially painful when opening various tabs as the limit is per browser and set to a very low number (6). The issue has been marked as "Won't fix" in Chrome and Firefox. This limit is per browser + domain, so that means that you can open 6 SSE connections across all of the tabs to www.example1.com and another 6 SSE connections to www.example2.com. (from Stackoverflow). When using HTTP/2, the maximum number of simultaneous HTTP streams is negotiated between the server and the client (defaults to 100).

Source: https://developer.mozilla.org/en-US/docs/Web/API/EventSource

 

Project structure

Edit
Server-sent events project created using Express.js.
Server-sent events project created using Express.js.

 

Project generator

Edit

Project was generated using this configuration (by using GENERATE button it is possible to download the project).

 

Project files

Edit

To generate src/main/resources/cert.pem and src/main/resources/key.pem files use the following command:

Hint: to know how to generate certificate files under Windows read this article.

 

src/main/resources/application.properties file:

 

src/main/resources/static/index.html file:

Note: event source can be closed by source.close() method call.

 

src/main/java/com/example/demo/DemoApplication.java file:

 

src/main/java/com/example/demo/MainController.java file:

 

pom.xml file:

 

Project compilation

Edit

To download dependencies and compile project use the following command:

 

Server running

Edit

To run server use the following command:

Then, to see the final effect, open the link in the web browser: https://localhost:8443

 

Example preview:

Server-sent events application tested under web browser.
Server-sent events application tested under web browser.

 

See also

Edit
  1. OpenSSL - generate localhost *.pem certificate under Windows

References

Edit
  1. Server-sent events - MDN Docs
  2. EventSource - MDN Docs

Alternative titles

  1. Spring Boot 3 - server-sent events example
  2. Spring Boot 3 - server events example
  3. Spring Boot 3 - server events example using Spring MVC
  4. Spring Boot 3 - SSE example using Spring MVC
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join