I have 2 websocket endpoints producing related messages:
“ws://localhost:8032/posts”
“ws://localhost:8032/comments”
Comments are guaranteed to be published after a referred post and there could be deletion events after which if there is a out of synch comment, it will result in an error.
I am trying to implement a simple client first without all the fancy stuff and while I am easily able to listen to one endpoint, listening to both at the same time makes my system behave in a weird way.
I have this config:
@Component
@RequiredArgsConstructor
public class WebSocketConfig {
private static final String postUri = "ws://localhost:8032/posts";
private static final String commentUri = "ws://localhost:8032/comments";
private final PostHandler postHandler;
private final CommentHandler commentHandler;
// @PostConstruct
// public void connectToWebSocketEndpoints() {
// WebSocketClient client = new StandardWebSocketClient();
//
// client.doHandshake(postHandler, postUri);
//
// WebSocketClient client2 = new StandardWebSocketClient();
// client2.doHandshake(commentHandler, commentUri);
// }
@Bean
public WebSocketConnectionManager postConnectionManager() {
WebSocketConnectionManager manager = new WebSocketConnectionManager(
new StandardWebSocketClient(),
postHandler,
postUri);
manager.setAutoStartup(true);
return manager;
}
@Bean
public WebSocketConnectionManager commentConnectionManager() {
WebSocketConnectionManager manager = new WebSocketConnectionManager(
new StandardWebSocketClient(),
commentHandler,
commentUri);
manager.setAutoStartup(true);
return manager;
}
}
I want to initialise the comment client a bit later. But no matter what, both clients come into affect at the same time.
What I tried so far:
- I tried adding dependentOn the first bean
- added thread.sleep
- Combined the beans into one bean for WebSocketConnectionManager and initialised them one by one
- Tried to initialise the client inside @PostContruct
In all cases, the behaviour is the same – both connections are established at the same time and they process messages in a burst.
How can I implement 2 independent listeners on 2 different websocket endpoints ? After the initial delay in initialization, I am ok for them to work in parallel.
Bonus:
Just for testing purposes, I initialised the second client via an endpoint. This behaviour was fine when I controlled the startup of second client but after a bit, the out of synch nature of the messages started to result in a lot of errors. Should I be consuming these messages with a single listener ?