Spring websockets:消息未发布

Spring websockets: message not published

我将 Spring WebSockets 与 STOMP 和 SockJS 一起用于前端。它工作正常,但我有另一个困难。

这是后端代码:

 @MessageMapping("/showAccountlist")
 @SendTo("/topic/accounts")
 public Account createPublishAccount(String name) throws Exception {

     return new Account(name);
 }

这是前端代码,运行良好,所有消息都会发布到所有客户端。

 stompClient.send("/app/showAccountlist", {}, name);

但是当我从 我的 java 后端调用我的后端方法 时,方法名称为

createPublishAccount("Carlos");

好像消息没有发布。任何解决方案?或者这不是它的工作方式,它只有在通过 SockJS 触发时才有效?

这是我的网络配置:

@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("/showAccountlist").withSockJS();
}

}

调用@SendTo注解的方法好像无法发送消息。

Spring推荐使用SimpMessagingTemplate发送消息的方式。例如在 convertAndSendToUser 方法 (http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/messaging/simp/SimpMessagingTemplate.html) 中,可以将目标作为参数(在您的情况下 /topic/accounts)。

请参阅 Spring 文档的摘录 (http://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html#websocket-stomp-handle-send):

What if you want to send messages to connected clients from any part of the application? Any application component can send messages to the "brokerChannel". The easiest way to do that is to have a SimpMessagingTemplate injected, and use it to send messages. Typically it should be easy to have it injected by type, for example:

@Controller
public class GreetingController {

    private SimpMessagingTemplate template;

    @Autowired
    public GreetingController(SimpMessagingTemplate template) {
        this.template = template;
    }

    @RequestMapping(path="/greetings", method=POST)
    public void greet(String greeting) {
        String text = "[" + getTimestamp() + "]:" + greeting;
        this.template.convertAndSend("/topic/greetings", text);
    }

}