Home > front end >  Is it possible to have different controllers for each stomp endpoint in Spring Boot?
Is it possible to have different controllers for each stomp endpoint in Spring Boot?

Time:12-14

Is it possible to assign different Controller or at least a different MessageMapping for each of the stomp endpoints? My goal is to have client1 connecting to /endpoint1 and client2 connecting to /endpoint2 without client1 being able to access any topics/queues of /endpoint2 and vice-versa (they are completely different applications). So they would be completely encapsulated implementations based on the endpoint to which they connect.

Bonus points for being able to use different Jackson ObjectMapper for each endpoint as well.

So far I have created a websocket configuration with 2 endpoints (/endpoint1 and /endpoint2):

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {
   @Override
   public void registerStompEndpoints(StompEndpointRegistry registry) {
      registry.addEndpoint("/endpoint1", "/endpoint2")
              .setAllowedOriginPatterns("*")
              .withSockJS();
   }

   // etc...

}

I also have a Controller which can process requests and send them to appropriate user response queue, but it's accessible from both endpoints:

@Controller
public class WebSocketController {
   @MessageMapping("/request")
   @SendToUser("/queue/response")
   public MyResponse handleMessage(MyRequest request) {
      // implementation
   }
}

Current behaviour: It doesn't matter which endpoint is my client connecting to in my current implementation, both can access the same topics, which is unwanted behavior.

CodePudding user response:

You should alter your application design so that clients would be only able to send messages to their respective STOMP destinations. You can name your STOMP destinations in a client-specific prefixed way such as:

/endpoint1/request
/endpoint2/request

You should then be able to define different @MessageMapping-annotated message handlers after the above naming pattern:

@Controller
public class WebSocketController {

    @MessageMapping("/endpoint1/request")
    @SendToUser("/endpoint1/queue/response")
    public MyResponse handleClient1Message(MyRequest request) {
      // process STOMP message from client 1
    }

    @MessageMapping("/endpoint2/request")
    @SendToUser("/endpoint2/queue/response")
    public MyResponse handleClient2Message(MyRequest request) {
      // process STOMP message from client 2
    }
}
  • Related