Websocket filtering messages for individual users

时间:2015-07-08 15:50:32

标签: spring spring-boot spring-websocket spring-messaging

I am creating a spring websocket application using RabbitMQ as a broker. Is there a way to filter what web socket messages a user will see on a channel?

Multiple people will be subscribed to the channel.

1 个答案:

答案 0 :(得分:2)

为了能够向在Spring中通过Web套接字连接的特定用户发送消息,您可以将@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()将替换你为频道名称选择的唯一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
  });

});