Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the Front end and RabbitMQ Real-time message push

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains the "front-end and RabbitMQ real-time message push how to achieve", the article explains the content is simple and clear, easy to learn and understand, now please follow the editor's ideas slowly in-depth, together to study and learn "front-end and RabbitMQ real-time message push how to achieve" it!

Real-time message push on the web side is often implemented in many ways, but it remains the same, and the underlying layer basically depends on the websocket,MQTT protocol.

RabbitMQ building

The basic construction of RabbitMQ will not be described in detail. It is not a big problem for Baidu to do it step by step. Here we mainly talk about two more important configurations.

1. Enable mqtt protocol

By default, RabbitMQ does not enable the MQTT protocol, so we need to manually open the relevant plug-ins, while RabbitMQ's MQTT protocol is divided into two types.

The first rabbitmq_mqtt is provided to interact with back-end services, corresponding to port 1883.

Rabbitmq-plugins enable rabbitmq_mqtt

The second rabbitmq_web_mqtt provides interactive use with the front end, corresponding to port 15675.

Rabbitmq-plugins enable rabbitmq_web_mqtt

When you see the following display in the RabbitMQ management background, it means that the MQTT protocol has been enabled successfully, and the middleware environment has been built.

Using the MQTT protocol, the default switch Exchange is amp.topic, and the topic we subscribe to will register a client queue in Queues, and routing Routing key is the topic we set.

Server message sending

The real-time message push on the web side is generally an one-way push, and the front end receives the message pushed by the server to display, so it is only possible to send the message.

1. Mqtt client dependency package

The implementation of two toolkits spring-integration-mqtt and org.eclipse.paho.client.mqttv3 are introduced.

Org.springframework.integration spring-integration-mqtt org.eclipse.paho org.eclipse.paho.client.mqttv3 1.2.02, message sender

The sending of messages is relatively simple, mainly applied to the @ ServiceActivator annotation. You need to pay attention to the messageHandler.setAsync attribute. If set to false, it may block when messages are sent in asynchronous mode.

@ Configurationpublic class IotMqttProducerConfig {@ Autowired private MqttConfig mqttConfig; @ Bean public MqttPahoClientFactory mqttClientFactory () {DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory (); factory.setServerURIs (mqttConfig.getServers ()); return factory;} @ Bean public MessageChannel mqttOutboundChannel () {return new DirectChannel () } @ Bean @ ServiceActivator (inputChannel = "iotMqttInputChannel") public MessageHandler mqttOutbound () {MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler (mqttConfig.getServerClientId (), mqttClientFactory ()); messageHandler.setAsync (false); messageHandler.setDefaultTopic (mqttConfig.getDefaultTopic ()); return messageHandler;}}

When MQTT provides the API for sending messages, you need to use the @ MessagingGateway annotation to provide a message gateway agent. The parameter defaultRequestChannel specifies the channel bound to send messages.

Three API interfaces can be implemented, payload is the message sent, the subject of the message sent by topic, and the quality of the qos message.

@ MessagingGateway (defaultRequestChannel = "iotMqttInputChannel") public interface IotMqttGateway {/ / send the message void sendMessage2Mqtt (String payload) to the default topic; / / send the message void sendMessage2Mqtt (String payload,@Header (MqttHeaders.TOPIC) String topic) to the specified topic; / / send the message to the specified topic and specify the quality of service parameter void sendMessage2Mqtt (@ Header (MqttHeaders.TOPIC) String topic, @ Header (MqttHeaders.QOS) int qos, String payload);} front-end message subscription

The front end is implemented using paho-mqtt mqttws31.js, a tool corresponding to the server, which is similar to the traditional websocket way, with the core method client = new Paho.MQTT.Client and various listening events, the code is relatively concise.

Note: to ensure the global uniqueness of the front and rear clientId, I will simply use random numbers here.

/ / mqtt protocol rabbitmq service var brokerIp = location.hostname; / / mqtt protocol port number var port = 15675; / / subject var topic = "push_message_topic" for accepting push messages; / / mqtt connection client = new Paho.MQTT.Client (brokerIp, port, "/ ws", "clientId_" + parseInt (Math.random () * 100,10)) Var options = {timeout: 3, / / timeout keepAliveInterval: 30 console.log / heartbeat onSuccess: function () {console.log (("connection succeeded ~")); client.subscribe (topic, {qos: 1}) }, onFailure: function (message) {console.log ("connection failed ~" + message.errorMessage));}}; / / considering the case of https if (location.protocol = = "https:") {options.useSSL = true;} client.connect (options) Console.log (("connected to" + brokerIp + ":" + port)); / / connection disconnection event client.onConnectionLost = function (responseObject) {console.log ("lost connection -" + responseObject.errorMessage);} / / receive message event client.onMessageArrived = function (message) {console.log ("accept subject: + message.destinationName +" message: "+ message.payloadString); $(" # arrivedDiv ") .append ("+ message.payloadString); var count = $(" # count "). Text (); count = Number (count) + 1 $("# count") .text (count);}; / / push to the specified topic function sendMessage () {var a = $("# message") .val (); if (client.isConnected ()) {var message = new Paho.MQTT.Message (a); message.destinationName = topic Client.send (message);}} Test

There is not much code in the front and back end, so let's test it and make a page to see the effect.

First, use postman to simulate the backend to send messages.

Http://127.0.0.1:8080/fun/sendMessage?message= I am a programmer something-topic=push_message_topic thank you for reading, the above is the "front-end and RabbitMQ real-time message push how to achieve" content, after the study of this article, I believe you have a deeper understanding of the front-end and RabbitMQ real-time message push how to achieve this problem, the specific use also needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report