Java 更改websocket范围(从应用程序更改为会话/视图)

Java 更改websocket范围(从应用程序更改为会话/视图),java,spring-boot,websocket,spring-websocket,spring-messaging,Java,Spring Boot,Websocket,Spring Websocket,Spring Messaging,我用教程创建了一个基本的web套接字 以下是一个配置: @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { con

我用教程创建了一个基本的web套接字

以下是一个配置:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
         registry.addEndpoint("/chat");
         registry.addEndpoint("/chat").withSockJS();
    }
}
这是消息处理控制器:

@MessageMapping("/chat")
@SendTo("/topic/messages")
public OutputMessage send(Message message) throws Exception {
    return new OutputMessage("Hello World!");
}
一切正常,但从我的调查来看,WebSockets在默认情况下似乎有一个应用范围(通过连接到频道,我可以看到来自所有用户的所有调用)

我想做的是能够只看到来自当前用户会话或当前视图的调用。
关于如何应用这些配置有什么想法吗?

我能够解决这个难题,所以我将与您分享我的发现

首先,我发现一个简单的内存消息代理无法处理以下信息:

    /*
     * This enables a simple (in-memory) message broker for our application.
     * The `/topic` designates that any destination prefixed with `/topic`
     * will be routed back to the client.
     * It's important to keep in mind, this will not work with more than one
     * application instance, and it does not support all of the features a
     * full message broker like RabbitMQ, ActiveMQ, etc... provide.
     */
但这是一种误导,因为它可以通过
@SendToUser
注释轻松实现。 另外,重要的是,现在在客户端,您需要在订阅频道时添加额外的前缀
/user/
,因此解决方案是:

  • 在服务器端:将
    @SendTo(“/topic/messages”)
    更改为
    @SendToUser(“/topic/messages”)
  • 在客户端:
    /topic/messages
    进入
    /user/topic/messages