我正在使用 RabbitMQ 作为代理创建一个 spring websocket 应用程序。有没有办法过滤用户将在 channel 上看到的网络套接字消息?
多人将订阅该 channel 。
最佳答案
为了能够向在 Spring 中通过 Web Sockets 连接的特定用户发送消息,您可以将 @SendToUser 注释与 SimpMessagingTemplate 结合使用
引用可以在这里找到
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html#websocket-stomp-user-destination
但简而言之(取自引用)
首先设置您的主题
@Controller
public class PortfolioController {
@MessageMapping("/trade")
@SendToUser("/queue/position-updates")
public TradeResult executeTrade(Trade trade, Principal principal) {
// ...
return tradeResult;
}
}
实现您自己的 UserDestinationResolver 或使用默认的
http://docs.spring.io/autorepo/docs/spring/4.1.3.RELEASE/javadoc-api/org/springframework/messaging/simp/user/DefaultUserDestinationResolver.html
这会将您的路径从/queue/position-updates 解析为唯一路径,例如/queue/position-updates-username1234
我的建议是使用 UUID 或类似的,以使其难以猜测
然后,当您想发送消息时,trade.getUsername() 将替换您为 channel 名称选择的唯一 ID
public void afterTradeExecuted(Trade trade) {
this.messagingTemplate.convertAndSendToUser(
trade.getUserName(), "/queue/position-updates", trade.getResult());
}
最后,在订阅时,您需要确保客户端订阅了正确的主题。这可以通过头或 Json 消息向用户发送队列后缀来完成。
client.connect('guest', 'guest', function(frame) {
var suffix = frame.headers['queue-suffix'];
client.subscribe("/queue/error" + suffix, function(msg) {
// handle error
});
client.subscribe("/queue/position-updates" + suffix, function(msg) {
// handle position update
});
});
关于spring - 单个用户的 Websocket 过滤消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31297657/