Sometimes our projects will use the instant messaging function, such as the customer service chat function in the e-commerce system, and in the process of payment, when the user pays successfully, the third-party payment service will call back our callback interface. At this time, we need to inform the front end of the payment success. RabbitMQ has recently been found to be a very convenient way to implement instant messaging. If you have no special business requirements, you can even do without writing back-end code. Today I will show you how to use RabbitMQ for instant messaging!

The MQTT protocol

Message Queuing Telemetry Transport (MQTT) is a lightweight communication protocol based on publish/subscribe mode. MQTT is based on TCP/IP. The biggest advantage of MQTT is that it can provide real-time, reliable messaging services for connecting remote devices with very little code and limited bandwidth.

MQTT related concepts

  • Publisher: The sender of messages, responsible for sending them.
  • Subscriber: The Subscriber of the message, responsible for receiving and processing the message.
  • Broker: A message Broker between a publisher and a subscriber. Various MQTT-enabled message middleware can act as a Broker.
  • Topic: Can be understood as a route in a message queue. After subscribing to a Topic, subscribers can receive messages sent to that Topic.
  • Payload B. It can be interpreted as the content of the sent message.
  • QoS(message Quality) : indicates the Quality of sending messages. QoS 0, QoS 1, and QoS 2 are described as follows: QoS 0(Almost Once) : indicates that messages are sent at most Once. QoS 1(Atleast Once) : ensures message arrival Atleast Once, but message duplication may occur. QoS 2(Exactly Once) : Ensures that the message arrives only Once.

Enable the MQTT function for RabbitMQ

To enable MQTT for RabbitMQ, install RabbitMQ and then enable the MQTT plug-in.

  • The first step is to install and start up RabbitMQ. For those of you who are not familiar with RabbitMQ, see 3 days of RabbitMQ Practical Tips, Something! ;
  • The MQTT plugin for RabbitMQ is disabled by default. Use the following command to enable it.
rabbitmq-plugins enable rabbitmq_mqtt
Copy the code
  • After successfully enabling the MQTT service, looking at the administrative console, we can see that the MQTT service is running on port 1883.

The MQTT client

We can test the instant messaging capabilities of MQTT using the MQTT client, the MQTTBox client tool.

  • Download and install the good MQTTBox, download address: workswithweb.com/mqttbox.htm…

  • Click the Create MQTT Client button to Create an MQTT Client;

  • Next, configure the MQTT client, including protocol port, connection user name, password and QoS.

  • Configure a subscriber, and the subscriber subscribes to the topic testTopicA, and we send messages to that topic;

  • Publishers publish messages to topics that subscribers can receive in real time.

The front end enables instant messaging directly

Since MQTTBox clients can im directly over RabbitMQ, can we im directly using the front-end technology? The answer is yes! Below we will implement a simple chat function through HTML +javascript, really do not write a line of back-end code to achieve instant messaging!

  • To enable MQTT Web support for RabbitMQ, run the following command:
rabbitmq-plugins enable rabbitmq_web_mqtt
Copy the code
  • Once enabled, looking at the administrative console, we can see that MQTT’s WEB service is running on port 15675;

  • The WEB side communicates with the MQTT service using a library called mqtt.js, project address: github.com/mqttjs/MQTT…

  • The implementation of the function is very simple, a single chat function, need to pay attention to the configuration of the MQTT service access address is: ws://localhost:15675/ws
Title
Copy the code

Target Topic: Send messages: Send empty

` `

  • TestTopicA = testTopicA = testTopicA = testTopicA = testTopicA = testTopicA = testTopicA = testTopicA = testTopicA = testTopicA http://localhost:8088/page/index? Topic = testTopicA subscribe to the second theme testTopicB, access address: http://localhost:8088/page/index? topic=testTopicB
  • Then send messages to each other, let’s see the effect!

Used in SpringBoot

When there are no special service requirements, the front-end can be directly connected to RabbitMQ for instant communication. But there are times when we need to notify the front end via the server, and that’s when we need to integrate MQTT into the application. Let’s look at how to use MQTT in the SpringBoot application.

  • First we need to add mqTT-related dependencies to pom.xml;
org.springframework.integration    spring-integration-mqtt
Copy the code
  • Add mqTT-related configuration in application.yml, including access address, user name and password, default topic information;
rabbitmq:  mqtt:    url: tcp://localhost:1883 username: guest password: guest defaultTopic: testTopic
Copy the code
  • Write a Java configuration class to read the configuration from the configuration file for easy use;
/** * Created by macro on 2020/9/15. */@Data@EqualsAndHashCode(callSuper = false)@Component@ConfigurationProperties(prefix = "rabbitmq.mqtt")public class MqttConfig {    /** * RabbitMQ connection user name */    private String username;    /** * RabbitMQ connection password */    private String password;    /** * RabbitMQ MQTT default topic */    private String defaultTopic;    /** * MQTT connection to RabbitMQ */    privateString url; }Copy the code
  • Add MQTT message subscriber related configurations, declare a ServiceActivator using the @serviceactivator annotation, and process subscription messages through MessageHandler;
/** * Created by macro on 2020/9/15. */@Slf4j@Configurationpublic class MqttInboundConfig {    @Autowired    private MqttConfig mqttConfig;    @Bean    public MessageChannel mqttInputChannel(a) {        return new DirectChannel();    }    @Bean    public MessageProducer inbound(a) {        MqttPahoMessageDrivenChannelAdapter adapter =                new MqttPahoMessageDrivenChannelAdapter(mqttConfig.getUrl(), "subscriberClient",                        mqttConfig.getDefaultTopic());        adapter.setCompletionTimeout(5000);        adapter.setConverter(new DefaultPahoMessageConverter());        // Set message quality: 0-> at most once; 1-> At least once; 2-> Only one adapter.setqos (1); adapter.setOutputChannel(mqttInputChannel()); return adapter; } @Bean @ServiceActivator(inputChannel = "mqttInputChannel") public MessageHandler handler() { return new MessageHandler() {@override public void handleMessage(Message> Message) throws MessagingException {// Processes subscription messages log.info("handleMessage : {}",message.getPayload()); }}; }}
Copy the code
  • Add MQTT message publisher configuration;
** * Created by macro on 2020/9/15. */@Configurationpublic class MqttOutboundConfig {    @Autowired    private MqttConfig mqttConfig;    @Bean    public MqttPahoClientFactory mqttClientFactory(a) {        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();        MqttConnectOptions options = new MqttConnectOptions();        options.setServerURIs(new String[] { mqttConfig.getUrl()});        options.setUserName(mqttConfig.getUsername());        options.setPassword(mqttConfig.getPassword().toCharArray());        factory.setConnectionOptions(options);        return factory;    }    @Bean    @ServiceActivator(inputChannel = "mqttOutboundChannel")    public MessageHandler mqttOutbound(a) {        MqttPahoMessageHandler messageHandler =                new MqttPahoMessageHandler("publisherClient", mqttClientFactory());        messageHandler.setAsync(true);        messageHandler.setDefaultTopic(mqttConfig.getDefaultTopic());        return messageHandler;    }    @Bean    public MessageChannel mqttOutboundChannel(a) {        return new DirectChannel();    }}
Copy the code
  • Add an MQTT gateway for sending messages to topics;
/** * Created by macro on 2020/9/15. */@Component@MessagingGateway(defaultRequestChannel = "mqttOutboundChannel")public interface MqttGateway {    /** * sends messages to the default topic */    void sendToMqtt(String payload);    /** * sends messages to the specified topic */    void sendToMqtt(String payload, @Header(MqttHeaders.TOPIC) String topic);    /** * sends messages to the specified topic and sets QOS */    void sendToMqtt(@Header(MqttHeaders.TOPIC) String topic, @Header(MqttHeaders.QOS) int qos, String payload); }Copy the code
  • Add an MQTT test interface to send messages to specific topics using the MQTT gateway;
/** * MQTT test interface * Created by macro on 2020/9/15. */@API (tags = "MqttController", description = "MQTT test interface ")@RestController@RequestMapping("/mqtt")public class MqttController {    @Autowired    private MqttGateway mqttGateway;    @PostMapping("/sendToDefaultTopic")    @apiOperation (" Send a message to the default topic ")    public CommonResult sendToDefaultTopic(String payload) {        mqttGateway.sendToMqtt(payload);        return CommonResult.success(null);    }    @PostMapping("/sendToTopic")    @apiOperation (" Send a message to a specified topic ")    public CommonResult sendToTopic(String payload, String topic) {        mqttGateway.sendToMqtt(payload, topic);        return CommonResult.success(null);    }}
Copy the code
  • Call the interface to send a message to the topic for testing;

  • The background receives the message and prints it.
2020- 09 -17 14:29:01.689  INFO 11192- [ubscriberClient] C.M.M. All tiny. Config. MqttInboundConfig: handleMessage: news from the web page2020- 09 -17 14:29:06.101  INFO 11192- [ubscriberClient] C.M.M. All tiny. Config. MqttInboundConfig: handleMessage: news from the web page2020- 09 -17 14:29:07.384  INFO 11192- [ubscriberClient] C.M.M. All tiny. Config. MqttInboundConfig: handleMessage: news from the web pageCopy the code

conclusion

Message-oriented middleware is more and more widely used. It can not only realize reliable asynchronous communication, but also realize instant communication. It is necessary to master a message-oriented middleware. If there are no special business requirements, the client or front end can directly use MQTT to connect to the messaging middleware to achieve instant messaging, when there are special requirements can also use SpringBoot integrated MQTT way to achieve, in short, messaging middleware is a good choice to achieve instant messaging!

Welcome to pay attention to the public number: Java treasure to receive more tutorial welfare