在Spring WebSocket中捕获会话ID

时间:2018-09-16 08:10:15

标签: java spring spring-boot websocket spring-websocket

我的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?

2 个答案:

答案 0 :(得分:0)

连接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标头供您考虑。

答案 1 :(得分:0)

简单。只需在任何类中添加此方法:

@EventListener
    private void handleSessionConnected(SessionConnectEvent event) {
        String sessionId = SimpAttributesContextHolder.currentAttributes().getSessionId();
    }