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

问题描述 投票:0回答:1

在我的应用程序中,我使用STOMP通过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个回答
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    
    }
} 
© www.soinside.com 2019 - 2024. All rights reserved.