Spring boot is an awesome “wrapper” which allows Spring projects to be created and run with minimal configuration and it makes development fun again. I was looking for a way to emit events from my Spring repositories to topics that consumers could subscribe to and came across spring boot websockets.
Add the below to your build.gradle:
Defining a Spring Repository:
To capture events emitted when entities are created and send them to a socket endpoint:
The above code will use the Spring SimpleMessagingTemplate to push the created user to a /topic/user topic.
Expose the above event handler through your Spring configuration:
Finally create a websocket configuration to define the broker and endpoint:
The above code does the following things:
1. Creates a simple broker.
2. Creates an endpoint /messages which accepts cross origin requests from all domains.
3. Enable SockJS fallback options.
Now you can connect to this websocket and subscribe to the topic as below: