spring websocket + rabbitmq stomp:我如何获得所有在线用户并断开某些用户的连接?

时间:2016-05-12 03:46:49

标签: spring websocket rabbitmq spring-websocket spring-messaging

如果是春季商店用户的websocket会话,怎么可以得到它,如果我使用someHandler将会话放在地图中,这意味着地图的大小可能大于10w +,我不认为它很好

SessionHandler.java

{{1}}
像这样: https://github.com/isaranchuk/spring-websocket-disconnect/blob/master/src/main/java/hello/SessionHandler.java

1 个答案:

答案 0 :(得分:1)

如下所示实现HandshakeInter。

public class HttpSessionIdHandshakeInterceptor implements HandshakeInterceptor {

    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(false);
            if (session != null) {
                attributes.put(SESSION_ATTR, session.getId());
            }
        }
        return true;
    }

    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                               WebSocketHandler wsHandler, Exception ex) {
    }
}

然后添加到端点。

public class WebSocketConfig extends 
      AbstractWebSocketMessageBrokerConfigurer {

public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/portfolio")
            .withSockJS()
            .setInterceptors(new HttpSessionIdHandshakeInterceptor());

}

... }

接下来,我们可以创建一个ChannelInterceptorAdapter,它使用会话ID来使用Spring Session更新上次访问的时间。例如:

@Bean public ChannelInterceptorAdapter sessionContextChannelInterceptorAdapter() {
return new ChannelInterceptorAdapter() {
    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        Map<String, Object> sessionHeaders = SimpMessageHeaderAccessor.getSessionAttributes(message.getHeaders());
        String sessionId = (String) sessionHeaders.get(SESSION_ATTR);
        if (sessionId != null) {
            Session session = sessionRepository.getSession(sessionId);
            if (session != null) {
                sessionRepository.save(session);
            }
        }
        return super.preSend(message, channel);
    }
};

}