繁体   English   中英

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

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

在我的应用程序中,我使用 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");
    }
}

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

您可以在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    
    }
} 

暂无
暂无

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

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