【问题标题】:Spring STOMP WebSocket session disconnect handler / reconnection handlingSpring STOMP WebSocket 会话断开处理程序/重新连接处理
【发布时间】:2019-07-09 10:10:04
【问题描述】:

在我的应用程序中,我使用 STOMP over WebSocket 进行微服务之间的通信,我正在尝试实现会话断开事件侦听器以重新建立微服务之间的连接。根据 Spring 的文档,SessionDisconnectEvent 应该在 STOMP 会话结束时发布。这就是我试图捕捉事件的方式:

@Component
public class SessionDisconnectListener implements ApplicationListener<SessionDisconnectEvent> {
    @EventListener
    @Override
    public void onApplicationEvent(SessionDisconnectEvent  applicationEvent) {
        System.out.println("SESSION " + applicationEvent.getSessionId() + " DISCONNECTED");
    }
}

我可以在我的应用程序中看到会话状态从已连接变为已断开,但不幸的是,此方法是较新调用的。如何正确捕获会话断开事件?

【问题讨论】:

    标签: java spring websocket spring-websocket stomp


    【解决方案1】:

    您可以在 StompSessionHandlerAdapter 中实现断开连接处理程序。在你需要实现handleTransportError(session, exception)的适配器中,所有的连接失败事件都会通过这个方法,你应该在那里实现你的断开处理程序。您可以根据传递的异常或通过检查会话的连接状态来确定连接是否丢失,我个人更喜欢后者。

    AtomicBoolean reconnecting = new AtomicBoolean();
    
    @public void handleTransportError(StompSession session, Throwable exception) {
        If (!session.isConnected()) {
            If (reconnecting.compareAndSet(false, true)) {  //Ensures that only one thread tries to reconnect
                try {
                    reestablishConnection();
                } finally {
                    reconnecting.set(false);
                }
            }
        } else {} //Log exception here
    } 
    private void reestablishConnection() {
        boolean disconnected = true;
        while (disconnected) {
            try {
                TimeUnit.SECONDS.sleep(sleepTime); //Specify here for how long do you want to wait between each reconnect attempt
            } catch (Exception e) {}  //If an exception happens here then the service is most likely being shut down
            try {
                stompClient.connect(url, this).get();
                disconnected = false;
            } catch (Exception e) {} //Add logging etc. here    
        }
    } 
    

    【讨论】:

      猜你喜欢
      • 2019-04-14
      • 1970-01-01
      • 1970-01-01
      • 2013-12-21
      • 2012-12-27
      • 1970-01-01
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多