【问题标题】:Listen to a queue in a controller Spring MVC and Spring web socket在控制器 Spring MVC 和 Spring Web 套接字中侦听队列
【发布时间】:2016-07-20 09:27:33
【问题描述】:

我有一个场景,我们有一个使用 Spring MVC 和 spring web-socket 的应用程序。我想在一个监听消息的控制器中编写一个方法,然后一旦它收到该消息,它将转换并将其发送到用户在客户端监听的另一个队列。

客户端代码看起来像

    var connect = function() {
    var socket = new SockJS(webSocketUrl);
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function(frame) {

        console.log('Connected: ' + frame);
        stompClient.subscribe("/user/queue/test", function(data){ 
            alert(data);               
    }
    }
    );

我不确定 java 代码应该是什么样子

@SubscribeMapping("/queue/cluwe.controller.sign") 
public void signMessagesAggregator() {
    String blah = "test";
    simpMessageSendingOperations.convertAndSendToUser("userId", "/queue/test", blah);
}

我知道 java 部分是错误的,但是我在 spring-websockets 中找不到任何文档,这些文档在 java 中具有 stompClient.subscribe 之类的东西。有什么想法吗?

【问题讨论】:

    标签: java spring-mvc stomp spring-websocket sockjs


    【解决方案1】:

    配置

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

    发送消息

    @Autowired
    SimpMessagingTemplate template;
    //all users
    template.convertAndSend("/topic/mytopic/", "message")
    //especific user
    template.convertAndSendToUser("userId", "/topic/mytopic/", "message"));
    

    客户端

      stomp.connect('/websocket', {})
        .then(function() {
          stomp.subscribe('/topic/mytopic/', function(message) {
            console.log('message' + message)
          });
        });
    

    【讨论】:

      【解决方案2】:

      会是这样的:

      @Controller
      public class GreetingController {
      
          @MessageMapping("/hello")
          @SendTo("/topic/events")
          //subscribed to /hello and sends Greeting to /topic/events
          public Greeting greeting(HelloMessage message) throws Exception {
              Thread.sleep(3000); // simulated delay
              return new Greeting("Hello, " + message.getName() + "!");
          }
      
      }
      

      应使用@EnableWebSocketMessageBroker 配置应用程序,并且需要配置代理。看看tutorial

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-14
        • 1970-01-01
        • 2023-03-29
        • 2021-05-13
        • 1970-01-01
        • 1970-01-01
        • 2017-09-03
        相关资源
        最近更新 更多