我有一个Spring Session和Spring Websockets的应用程序。我使用websocket handshake interceptor为websocket session设置属性
public class WebsocketHandshakeInterceptor implements HandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
HttpSession session = servletRequest.getServletRequest().getSession(true);
if (session != null) {
attributes.put(ApplicationConstants.HTTP_SESSION_ID_KEY, session.getId());
attributes.put(ApplicationConstants.HTTP_SESSION_KEY, session);
}
}
return true;
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler wsHandler, Exception ex) {
}
}
然后我抓住了SessionConnectEvent
。事件包含所需信息(http会话和会话ID)。但会话在null
sessionRepository
@Component
public class WebSocketListener implements ApplicationListener<SessionConnectEvent> {
@Autowired
private MapSessionRepository sessionManager;
@Override
public void onApplicationEvent(SessionConnectEvent event) {
String httpSessionId
= event.getWebSocketSession().getAttributes().get(ApplicationConstants.HTTP_SESSION_ID_KEY).toString();
sessionManager.getSession(httpSessionId); //returns null
}
}
第一次调用返回null
,如果我尝试重新连接,则返回有效会话。你能告诉我我的错误吗?感谢。