Closing all WebSocket sessions using Spring GraphQL

Closing all WebSocket sessions using Spring GraphQL


0

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
2


1

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);
    }
}


-1

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



Leave a Reply

Your email address will not be published. Required fields are marked *