【问题标题】:Spring send message to Websocket Message BrokerSpring 向 Websocket 消息代理发送消息
【发布时间】:2016-06-29 02:39:36
【问题描述】:

我想向特定记录的 websocket 订阅者发送消息 - 当我的一个服务类中发生操作时。

我正在尝试阅读Spring Websocket documentation,但它对于如何让所有这些东西一起工作有点模棱两可。

这是我的设置文件(顺便说一句,这是扩展 jHipster):

WebsocketConfiguration.java

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableStompBrokerRelay("/queue/", "/topic/", "/exchange/");
        config.setApplicationDestinationPrefixes("/app");
        config.setPathMatcher(new AntPathMatcher("."));
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").withSockJS();
    }

WebsocketSecurity.java

@Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
    messages
        // message types other than MESSAGE and SUBSCRIBE
        .nullDestMatcher().authenticated()
        // matches any destination that starts with /rooms/
        .simpDestMatchers("/topic/tracker").hasAuthority(AuthoritiesConstants.ADMIN)
         .simpDestMatchers("/topic/**").authenticated()
        // (i.e. cannot send messages directly to /topic/, /queue/)
        // (i.e. cannot subscribe to /topic/messages/* to get messages sent to
        // /topic/messages-user<id>)
         .simpTypeMatchers(SimpMessageType.MESSAGE, SimpMessageType.SUBSCRIBE).denyAll()
        // catch all
        .anyMessage().denyAll();
}

控制器类(尝试实现一个简单的代理,我可以测试从 sockjs 订阅并接收应用程序其他地方生成的消息:

@MessageMapping("/ws")
@SendTo("/topic/sendactivity.{id}")
public void activity(@DestinationVariable string id, @Payload String message){
    log.debug("Sending command center: "+message);
}

@RequestMapping(value = "/updateactivity", method = RequestMethod.PUT)
public ResponseEntity<Membership> updateMembership(
        @RequestBody Membership membership) throws URISyntaxException {
    // ...
    String testString = "test";
    messagingTemplate.convertAndSend("/topic/commandcenter"+membership.getId().toString(), testString);
    // ...
}

当我在public void activity 方法上设置断点时,我什么也得不到?

【问题讨论】:

  • 你能分享一下 sockJS 客户端日志吗?无法查看发送了哪条消息以及它得到了什么样的响应。能不能也把org.springframework.web.socket放到DEBUG里,把相关的日志也分享一下?
  • @BrianClozel - 我什至还没有订阅频道 - 这会导致它不活跃吗?!我想在我运行convertAndSend 之后我应该在void activity 方法中打断点?

标签: spring jhipster spring-websocket


【解决方案1】:

使用消息传递模板向"/topic/commandcenterID" 发送消息会将该消息发送到消息代理,该消息代理会将该消息发送给订阅该主题的客户端。所以它不会流经你的活动方法。

当使用 @MessageMapping 带注释的方法时,您将它们声明为应用程序目标。因此,向"/app/ws" 发送消息应该映射到该方法。请注意,在这种情况下,我怀疑它是否会起作用,因为@MessageMapping 注释中的路径定义中缺少您期望作为方法参数的目标变量. 此外,@SendTo 注解实际上告诉 Spring 方法返回的值应该转换为消息并发送到给定的目的地。

看来你在这里混淆了,我认为你应该:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-02
    • 2016-12-19
    • 2014-08-28
    • 2016-04-28
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多