deg*_*ath 5 java websocket spring-boot spring-messaging spring-websocket
我用教程创建了一个基本的网络套接字。
这是一个配置:
@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();
}
}
Run Code Online (Sandbox Code Playgroud)
这是消息处理控制器:
@MessageMapping("/chat")
@SendTo("/topic/messages")
public OutputMessage send(Message message) throws Exception {
return new OutputMessage("Hello World!");
}
Run Code Online (Sandbox Code Playgroud)
一切正常,但根据我的调查,默认情况下 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.
*/
Run Code Online (Sandbox Code Playgroud)
但这是误导性的,因为它可以通过@SendToUser注释轻松实现。另外,重要的是现在在客户端,您需要/user/在订阅频道时添加额外的前缀,因此解决方案是:
@SendTo("/topic/messages")为@SendToUser("/topic/messages")./topic/messages进入/user/topic/messages.| 归档时间: |
|
| 查看次数: |
111 次 |
| 最近记录: |