Video in progress
The app uses an HTTP session (Spring Session, Redis). A user who works only over WebSocket gets logged out after 30 minutes. Why, and what do you do?
WebSocket messages aren't HTTP requests, so the HTTP session's lastAccessedTime isn't updated and it expires and is deleted. Spring Session's AbstractSessionWebSocketMessageBrokerConfigurer keeps the HTTP session alive on WebSocket messages and closes the WebSocket when the session is deleted.
📖 Answer
Scenario: a user opens the chat page and only chats. The browser didn't send a single HTTP request within 30 minutes. The session TTL in Redis ran out. On the next REST request there's a 401, and the user says "but I was just typing".
There's a reverse problem too: the user logged out or the session was deleted, but the WebSocket connection is still open and messages keep arriving.
Spring Session solves both:
@Configuration
@EnableWebSocketMessageBroker
public class WsConfig
extends AbstractSessionWebSocketMessageBrokerConfigurer<Session> {
@Override
protected void configureStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws");
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic", "/queue");
registry.setApplicationDestinationPrefixes("/app");
}
}
Note that it's configureStompEndpoints, not registerStompEndpoints: the parent class adds an interceptor that picks up the session ID in the handshake. After that every incoming message "touches" the HTTP session, and when the session is deleted, the WebSocket sessions that belong to it are closed.
One catch: this means a write to Redis on every message. For very active clients that's a noticeable load. So sometimes I do it differently: I authenticate the WebSocket with a token and separate it from the HTTP session entirely, and while the client is active it occasionally refreshes the session with a light REST request. Which way depends on the project, but you can't ignore the fact that the two sessions don't know about each other.
Sign up to mark studied questions and save your progress.