简体   繁体   English

Spring STOMP WebSocket 会话断开处理程序/重新连接处理

[英]Spring STOMP WebSocket session disconnect handler / reconnection handling

In my application I'm using STOMP over WebSocket for communication between microservices, I'm trying to implement session disconnect event listener to reestablish connection between microservices.在我的应用程序中,我使用 STOMP over WebSocket 进行微服务之间的通信,我正在尝试实现会话断开事件侦听器以重新建立微服务之间的连接。 According to Spring's documentation SessionDisconnectEvent should be published when a STOMP session ends.根据 Spring 的文档SessionDisconnectEvent应该在 STOMP 会话结束时发布。 That's how I've tried to catch the event:这就是我试图捕捉事件的方式:

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

I can see in my application that the session status changes from connected to disconnected but unfortunately this method is newer invoked.我可以在我的应用程序中看到会话状态从已连接更改为已断开连接,但不幸的是,此方法是较新调用的。 How can I properly catch session disconnect event?如何正确捕获会话断开事件?

You can implement a disconnect handler in your StompSessionHandlerAdapter .您可以在StompSessionHandlerAdapter实现断开连接处理程序。 In the adapter you need to implement handleTransportError(session, exception) , all connection failure events will go through this method and you should implement your disconnect handler there.在您需要实现handleTransportError(session, exception)的适配器中,所有连接失败事件都将通过此方法,您应该在那里实现断开连接处理程序。 You can determine whether connection has been lost based on the passed exception or by checking the connection status of your session, I personally prefer latter.您可以根据传递的异常或通过检查会话的连接状态来确定连接是否丢失,我个人更喜欢后者。

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    
    }
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM