2016-09-24 2 views
5

私はthisチュートリアルを使用しています。現在のセッション数を取得する方法を理解しようとしています。私WebSocketConfigは(コピーおよびチュートリアルから貼り付ける)、このようになりますSpring websocket - セッション数を取得する方法

@Configuration 
@EnableWebSocketMessageBroker 
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { 

    @Override 
    public void configureMessageBroker(MessageBrokerRegistry config) { 
     config.enableSimpleBroker("/topic"); 
     config.setApplicationDestinationPrefixes("/app"); 
    } 

    @Override 
    public void registerStompEndpoints(StompEndpointRegistry registry) { 
     registry.addEndpoint("/gs-guide-websocket").withSockJS(); 
    } 

} 

私は(再びコピーして貼り付け)このクラスの内部セッションの数を知りたいのです:

@Controller 
public class GreetingController { 


    @MessageMapping("/hello") 
    @SendTo("/topic/greetings") 
    public Greeting greeting(HelloMessage message) throws Exception { 
     Thread.sleep(1000); // simulated delay 
     return new Greeting("Hello, " + message.getName() + "!"); 
    } 

} 

websocketに現在のセッション(ユーザー、接続)の数を簡単に取得する方法はありますか?

編集:

Set<String> mySet = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>()); 

@EventListener 
private void onSessionConnectedEvent(SessionConnectedEvent event) { 
    StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage()); 
    mySet.add(sha.getSessionId()); 
} 

@EventListener 
private void onSessionDisconnectEvent(SessionDisconnectEvent event) { 
    StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage()); 
    mySet.remove(sha.getSessionId()); 
} 

私は今mySet.size()とのセッションの数を取得することができます:

はここに私のソリューションです。

答えて

2

ApplicationContextイベントを使用することができます。すべての接続、サブスクリプションまたはその他のアクションは、特別なイベントを発生させます。 SessionConnectEvent、SessionConnectedEvent、SessionSubscribeEventなどです。

完全なドキュメントは、このイベントのいずれかが発射されたとき、あなたは独自のロジックで、それを扱うことができhere

です。

+0

ありがとうございます!私は元の投稿を編集しました。 –

関連する問題