Search code examples
javaspringstompspring-websocket

Spring websocket - send messages to user destinations from outside the websocket server


Use case

I have one tomcat REST application which acts as an API gateway to a number of other applications behind it. I want to add websocket support to the tomcat application for sending notification updates per every user session. These notification updates would come from one of the other applications which does not have user session context but knows to which user it should send update (if this user currently has an open session).

So to be clear - I want just one websocket server and one (or more) application that just produces the messages to be sent to the user sessions.

My research

It's clear to me that I have to use the full featured broker support with STOMP as a subprotocol. We already use rabbit for the communication so it is the obvious choice.

The documentation states that "the STOMP broker relay also creates a separate TCP connection for every connected WebSocket client." It is a separate connection per user session, not per user. Also, when the sending side is within the same application (the one responsible for handling the user sessions), a separate queue is created per session. I suppose that the rest of my applications that want to send messages must somehow know about the currently active sessions and send the messages to the corresponding queues at the broker.

Possible solutions that I found

This issue in the Spring Jira is more or less connected to my problem. One of the possible solutions is to implement a distributed UserSessionRegistry.

The other one is to use the option provided as a resolution to the same issue - to enable broadcasting messages with unresolved user destinations. But in this case all of my applications will receive these broadcasting messages. And I want only the previously mentioned API gateway application to receive them (it will be the only one exposed to the clients and opening and closing user sessions).

So, what is the correct approach to this problem?


Solution

  • I want to add websocket support to the tomcat application

    The "tomcat application" being the Tomcat REST API gateway? I don't see why a full-featured broker would be required, or at least it seems unrelated.

    The application server that originates the updates needs some way to notify the gateway/websocket server which would in turn broadcast the message to subscribers. The gateway/webSocket could accept calls over HTTP, i.e. a plain @RequestMapping method that handles request by broadcasting via SimpMessagingTemplate.