I’m working on a Spring GraphQL (newest spring-boot-starter-graphql) project and I’m using WebSocket to establish subscriptions. However, I’m having trouble finding a way to close all WebSocket sessions programmatically.
I’ve looked into the documentation and searched for examples, but I couldn’t find a clear solution specific to Spring GraphQL. Most of the resources I found were related to general WebSocket implementations or STOMP.
Framework has a handler (GraphQlWebSocketHandler#WebMvcSessionInfo) that wraps WebSocketSession and places it in an internal sessionInfoMap that is not shared externally.
I want to make sure that all active sessions are properly terminated when a specific event occurs.
Any help or code examples demonstrating the approach would be greatly appreciated. Thank you!
2 Answers
I found the solution by extending GraphQlWebSocketHandler and collecting web socket sessions in bean collection.
@Component
class CustomGraphqlWebSocketHandler extends GraphQlWebSocketHandler {
private final Collection<WebSocketSession> sessions;
CustomGraphqlWebSocketHandler(WebGraphQlHandler graphQlHandler, HttpMessageConverter<?> mappingJackson2HttpMessageConverter,
Collection<WebSocketSession> sessions) {
super(graphQlHandler, mappingJackson2HttpMessageConverter, Duration.ofSeconds(5));
this.sessions = sessions;
}
@Override
public void afterConnectionEstablished(WebSocketSession session) {
sessions.add(session);
super.afterConnectionEstablished(session);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
sessions.remove(session);
super.afterConnectionClosed(session, closeStatus);
}
}
You saved my day, this solution is working perfectly fine, just want to know how this resolved my Websocket connection issues, why can’t the predefined class GraphQlWebSocketHandler able to handle the connections Why do we need a custom class ?
However thanks Mustard Tiger!
1
-
pavithran, this does not provide an answer to the question. You can search for similar questions, or refer to the related and linked questions on the right-hand side of the page to find an answer. If you have a related but different question, ask a new question, and include a link to this one to help provide context. See: Ask questions, get answers, no distractions
– M–24 mins ago