Exercise 3 - Server Sent Events
Last updated
Last updated
In this lab you'll learn how to expose streaming endpoints so that web applications are notified via Server Sent Events.
The web application 'Web-App' receives notifications from the 'Web-API' service.
Let's take a look at the JavaScript code which consumes the server side events.
A new EventSource is created by passing in the the URL of the streaming endpoint. The function source.onmessage is invoked when the events arrive. In our case this triggers the reload of the last articles.
The sample already comes with a working endpoint. Let's delete the file and recreate it from scratch.
Add the package name, the import statements and the empty class.
In Lab 2 you saw how to publish messages to the in-memory channel 'stream-new-article'. A publisher to this channel can easily be injected via @Inject and @Channel.
Last, but not least, add the implementation of the streaming endpoint. The media type is MediaType.SERVER_SENT_EVENTS and the annotation @SseElementType defines the type.
Once you've entered everything the class should look like this.
Exit the Editor via 'Ctrl-X', 'y' and 'Enter'.
On the 'Builds' page wait until the new build has been completed.
Once completed, delete the 'Web-API' pod which causes a new pod with the latest image to be started.
Make sure all four pods in the 'cloud-native-starter' project are running. Note that it takes a couple of minutes until this happens.
To launch the application get the URLs via the following command.
Open the web application in a browser. Then invoke the curl post command. The web application should show the new entry.