我的WebSocketConfig
课程是
@EnableWebSocket
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker( MessageBrokerRegistry registry )
{
registry.enableSimpleBroker("/topic", "/queue");
registry.setApplicationDestinationPrefixes("/user");
registry.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints( StompEndpointRegistry stompEndpointRegistry )
{
stompEndpointRegistry.addEndpoint("/ws").withSockJS();
stompEndpointRegistry.addEndpoint("/ws");
}
}
如何在建立连接时获取WebSocket会话ID?
连接STOMP会话时,执行以下代码:
else if (StompCommand.CONNECTED.equals(command)) {
this.stats.incrementConnectedCount();
accessor = afterStompSessionConnected(message, accessor, session);
if (this.eventPublisher != null && StompCommand.CONNECTED.equals(command)) {
try {
SimpAttributes simpAttributes = new SimpAttributes(session.getId(), session.getAttributes());
SimpAttributesContextHolder.setAttributes(simpAttributes);
Principal user = getUser(session);
publishEvent(this.eventPublisher, new SessionConnectedEvent(this, (Message<byte[]>) message, user));
}
finally {
SimpAttributesContextHolder.resetAttributes();
}
}
}
注意SessionConnectedEvent
与@EventListener
和SimpAttributesContextHolder
听。您可以使用sessionId
中的静态API访问该事件监听器中的SimpAttributesContextHolder
。
另一方面,事件中提到的消息有一个特定的simpSessionId
标题供您考虑。