WebSocket 集成
Spring Session 提供了与 Spring WebSocket 支持的透明集成。
| Spring Session 的 WebSocket 支持仅与 Spring 的 WebSocket 支持相配合。 具体来说,它无法直接使用 JSR-356,因为 JSR-356 没有拦截 WebSocket 消息的机制。 |
为什么选择Spring Session和WebSockets?
那么,为什么我们用WebSockets时还需要Spring Session呢?
考虑一个电子邮件应用,它通过HTTP请求完成大部分工作。
不过,它还内置了一个基于WebSocket API的聊天应用。
如果用户正在与某人积极聊天,我们不应超时HttpSession因为这会是一个相当糟糕的用户体验。
然而,这正是JSR-356所做的。
另一个问题是,根据JSR-356,如果HttpSession超时,任何用该方法创建的WebSocketHttpSession并且应强制关闭认证用户。
这意味着,如果我们在应用程序中主动聊天且没有使用 HttpSession,我们也会断开对话连接。
WebSocket 的使用
WebSocket示例提供了一个如何将Spring Session与WebSockets集成的工作示例。 你可以按照接下来几个标题中描述的集成基础步骤作,但我们鼓励你在与自己的应用集成时,遵循详细的WebSocket指南。
HttpSession集成
在使用WebSocket集成之前,你应该确保你已经有了HttpSession集成先工作。
Spring配置
在典型的 Spring WebSocket 应用中,你会实现WebSocketMessageBrokerConfigurer.
例如,配置可能如下:
@Configuration
@EnableScheduling
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
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支持。 以下示例展示了如何实现:
@Configuration
@EnableScheduling
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractSessionWebSocketMessageBrokerConfigurer<Session> { (1)
@Override
protected void configureStompEndpoints(StompEndpointRegistry registry) { (2)
registry.addEndpoint("/messages").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/queue/", "/topic/");
registry.setApplicationDestinationPrefixes("/app");
}
}
要连接春季课程的支持,我们只需要改变两点:
| 1 | 而不是实现WebSocketMessageBrokerConfigurer,我们延展AbstractSessionWebSocketMessageBrokerConfigurer |
| 2 | 我们会重新命名registerStompEndpoints方法configureStompEndpoints |
什么会AbstractSessionWebSocketMessageBrokerConfigurer幕后工作?
-
WebSocketConnectHandlerDecoratorFactory作为WebSocketHandlerDecoratorFactory自WebSocketTransportRegistration. 这确保了习惯会话连接事件是包含WebSocketSession. 这WebSocketSession是结束任何在春季会话结束时仍然开放的WebSocket连接所必需的。 -
会话存储器MessageInterceptor作为握手拦截者每一个StompWebSocketEndpointRegistration. 这确保了会期被添加到WebSocket属性中,以便更新最后访问时间。 -
会话存储器MessageInterceptor作为通道拦截者前往我们的入境频道注册. 这确保每次收到入站消息时,我们Spring Session的最后访问时间都会被更新。 -
WebSocketRegistryListener作为春豆诞生。 这确保了我们拥有所有会期对应WebSocket连接的ID。 通过维护这种映射,我们可以在春季会话(HttpSession)结束时关闭所有WebSocket连接。