notify the client from the MQ Listener

I am using web-sockets using Spring.

Here is my controller. A simple controller, which would accept a result object and return a result object with populated values. It would publish message to the STOMP topic subscribers "/topic/update".

@Controller
public class ReportController {

    @MessageMapping("/charthandler")
    @SendTo("/topic/update")
    public Result pushMessage(Result r) throws Exception {
        Thread.sleep(3000); // simulated delay
        Result result = new Result();
        result.setTitle("ChartsPage");
        return result;
    }

}

My Spring Configuration file:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

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

    @Bean
    public WebSocketHandler chartHandler() {
        return new ChartHandler();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

}

I have the following code in javascript, which creates a STOMP Web Socket Client. It is subscribing to the '/topic/update'

var socket = new SockJS('/reportapplication/charthandler/');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
  console.log('Connected: ' + frame);
  stompClient.subscribe('/topic/update', function(result) {
    console.log(JSON.parse(result.body).title);
  });
});

Now i am planning to add a listener(java and not in javascript) which would listen to the Rabbit MQ message, i want to pass the message object to my controller and push all the message to the Web Socket Clients.

I am not sure how to notify all my web-socket clients , when the message is arrived at my MQ listener. How will i do that?

Is it a good way to create an instance of report controller and call the pushMessage to notify all my web socket clients.

ReportController controller = new ReportController();
controller.pushMessage(report);

Also i'm not sure, if this works. I will try that. I want to know if there is a better approach.

Is there a better approach or better way of doing this?


Maybe if you look at the response Artem Bilan has provided to the following question: Spring, how to broadcast message to connected clients using websockets?

So if your java listener to the Rabbit MQ message is in a service then you can do the following in the same service and call the sendTo marked WS notification endpoint and pass on expected message to go out to the WS clients listening.

@Autowired
private SimpMessagingTemplate brokerMessagingTemplate;
.......
this.brokerMessagingTemplate.convertAndSend("/topic/greetings", "foo");
链接地址: http://www.djcxy.com/p/44776.html

上一篇: Tornado TCP服务器/客户端进程通信

下一篇: 从MQ Listener中通知客户端