Building applications with @EventListener

To play with the Publish-Subscribe pattern in Spring Framework, let's do an exercise. In turn, assume that we have to implement a simple web service that shows the current temperature in the room. For this purpose, we have a temperature sensor, which sends events with the current temperature in Celsius from time to time. We potentially want to have both mobile and web applications, but for the sake of conciseness, we are implementing only a simple web application. Furthermore, as questions of communication with microcontrollers are out of the scope of this book, we are simulating a temperature sensor using a random number generator.

To make our application following the reactive design, we cannot use an old pulling model for data retrieval. Fortunately, nowadays we have some well-adopted protocols for asynchronous message propagation from a server to a client, namely WebSockets and Server-Sent Events (SSE). In the current example, we will use the last one. The SSE allows a client to receive automatic updates from a server, and is commonly used to send message updates or continuous data streams to a browser. With the inception of HTML5, all modern browsers have a JavaScript API called EventSource, which is used by clients who request a particular URL to receive an event stream. The EventSource also autoreconnects by default in the case of communication issues. It is important to highlight that SSE is an excellent candidate for fulfilling communication needs between components in the reactive system. On par with WebSocket, SSE is used a lot in this book.

To read more about Server-Sent Events, please read the chapter of High Performance Browser Networking by Ilya Grigorik at https://hpbn.co/server-sent-events-sse/.

Also, the following article by Mark Brown gives a good comparison between WebSockets and Server-Sent Events:
https://www.sitepoint.com/real-time-apps-websockets-server-sent-events/
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.9.197