Java/Tomcat: how to handle WebSocket setup complet

2019-07-07 09:57发布

I have the following scenario: few Tomcat instances with the same application need to connect between each other on startup. For connection between servers, WebSockets (JSR-356) are used. When Tomcat has started, I need to initiate the establishment with another server.

How can I handle the most correctly, that internal WebSockets mechanism is up and I can start using WebSockets?

Application is based on Spring 4.

I tried this Execute method on startup in spring, this How to add a hook to the application context initialization event? and this Tomcat after Startup Event with spring .

All this approaches are cool but seems that on that moments WebSockets are still not ready to be used. Next exception is thrown:

javax.websocket.DeploymentException: The HTTP request to initiate the WebSocket connection failed    
at org.apache.tomcat.websocket.WsWebSocketContainer.connectToServer(WsWebSocketContainer.java:373)
at org.apache.tomcat.websocket.WsWebSocketContainer.connectToServer(WsWebSocketContainer.java:201)
at org.apache.tomcat.websocket.WsWebSocketContainer.connectToServer(WsWebSocketContainer.java:222)
...
Caused by: java.util.concurrent.TimeoutException
at sun.nio.ch.PendingFuture.get(PendingFuture.java:197)
at org.apache.tomcat.websocket.WsWebSocketContainer.processResponse(WsWebSocketContainer.java:599)
at org.apache.tomcat.websocket.WsWebSocketContainer.connectToServer(WsWebSocketContainer.java:343)

For now, as a workaround, I use 3 seconds delays in WebServlet's init() method before establishing the connection but it is kinda hack I would like to avoid.

Any ideas? Thanks!

1条回答
男人必须洒脱
2楼-- · 2019-07-07 10:47

I have solved it just by setting connection establishment into separate thread. Without separate thread, it blocks the continue of Tomcat startup. Hope it will help one day to somebody.

查看更多
登录 后发表回答