5、WebSocket集成
Spring Session提供了和Spring Websocket透明集成的支持。
Spring Session的Websocket支持仅适用于Spring的Websocket支持,具体来说他不能直接支持JSR-356。这是由于JSR-356没有拦截进入Websocket消息的机制。
5.1. 为什么要集成Spring Session和Websocket?
为什么在使用Websocket的时候我们需要Spring Session呢?
考虑一个大多数工作都是通过HTTP请求来完成的Email应用,然而,这个应用也嵌入了一个通过Websocket来完成工作的聊天应用。如果一个用户正在和另外的人活跃的聊天,我们的HttpSession就不应该超时,因为这将会是一个非常糟糕的体验。然而,JSR-356就这样做了。
另外一个问题就是根据JSR-356,如果HttpSession超时,所有使用这个HttpSession创建的WebSocket和已认证的用户都会被强制关闭。那就意味着如果我们正在我们的应用中活跃的聊天且我们没有使用HttpSession,那一会儿之后我们将会从我们的会话中断开连接。
5.2. Websocket使用
WebSocket 样例(https://github.com/spring-projects/spring-session/tree/2.0.0.M4/samples/boot/websocket)提供了一个如何整合Spring Session和WebSocket的可执行样例。你可以按照以下的基础步骤集成,但是在你集成自己的应用时,推荐遵循详细的WebSocket指南。
5.2.1. HttpSession集成
使用WebSocket集成之前,你首先应该确定你已经集成HttpSession且能够正常工作。
5.2.2. Spring配置
在典型的Spring WebSocket应用中,用户需要继承AbstractWebSocketMessageBrokerConfigurer。比如,配置看起来如下:
@Configuration
@EnableScheduling
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/messages").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/queue/", "/topic/");
registry.setApplicationDestinationPrefixes("/app");
}
}
我们可以很容易的更新我们配置去使用Spring Session的WebSocket支持。例如:
src/main/java/samples/config/WebSocketConfig.java
@Configuration
@EnableScheduling
@EnableWebSocketMessageBroker
public class WebSocketConfig
extends AbstractSessionWebSocketMessageBrokerConfigurer<Session> {
protected void configureStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/messages").withSockJS();
}
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/queue/", "/topic/");
registry.setApplicationDestinationPrefixes("/app");
}
}
在Spring Session支持中,我们只需要改变两件事情:
- 我们继承AbstractSessionWebSocketMessageBrokerConfigurer代替AbstractWebSocketMessageBrokerConfigurer 。
- 重命名registerStompEndpoints方法为configureStompEndpoints
AbstractSessionWebSocketMessageBrokerConfigurer在幕后做了什么呢?
- WebSocketConnectHandlerDecoratorFactory作为WebSocketHandlerDecoratorFactory被添加到WebSocketTransportRegistration。这就确保了包含WebSocketSession的SessionConnectEvent可以被自动启动。Spring Session终止之后,WebSocketSession需要去终止所有开启的WebSocket链接。
- SessionRepositoryMessageInterceptor作为HandshakeInterceptor被添加到StompWebSocketEndpointRegistration中。这就确保了会话已经被添加到WebSocket的属性中,以便更新上一次访问的时间。
- SessionRepositoryMessageInterceptor作为ChannelInterceptor被添加到我们的入站ChannelRegistration中。这就确保每次入站消息都会被接收,Spring Session的最后一次访问时间也会被更新。
- WebSocketRegistryListener作为一个Spring Bean被创建。这就确保了我们的所有Session id都会被映射到一个关联的WebSocket链接。通过维护这个映射,当Spring Session终止的时候我们就可以关闭所有的WebSocket链接。
原文:https://docs.spring.io/spring-session/docs/2.0.0.M4/reference/html5/#websocket