This is the sixth day of my participation in the August More text Challenge. For details, see: August More Text Challenge


Related articles

RabbitMQ series: RabbitMQ series


preface

  • What is a message queue?

    • A Message, “Message,” refers to data that is passed between applications. Messages can be simple, such as containing only text strings, or more complex, including embedded objects.
    • Message Queue is a communication mode between applications. Messages can be returned immediately after being sent. The Message system ensures the reliable delivery of messages. A publisher simply publishes messages to MQ regardless of who gets them, and a consumer simply retrieves messages from MQ regardless of who publishes them. In this way, neither the publisher nor the user needs to know that the other exists.
  • Why use message queues?

    • For example, a large number of INSERT, UPDATE and other requests arrive at MySQL at the same time, leading to numerous row locks and table locks, and even the request pile up too much at last. This triggers a Too many connections error. By using message queues, we can process requests asynchronously, thus relieving the stress on the system.
  • The characteristics of the RabbitMQ

    • Reliability
      • RabbitMQ uses a number of mechanisms to ensure reliability, such as persistence, transport acknowledgment, and publish acknowledgment.
    • Flexible Routing
      • Messages are routed through Exchange before they are queued. RabbitMQ already provides some built-in Exchange implementations for typical routing functions. For more complex routing capabilities, you can bind multiple Exchanges together and also implement your own Exchange through a plug-in mechanism.
    • Message Clustering
      • Multiple RabbitMQ servers can be clustered to form a logical Broker.
    • Highly Available Queues
      • Queues can be mirrored on the machines in the cluster, allowing them to remain available in the event of a partial node failure.
    • Multi-protocol
      • RabbitMQ supports multiple message queuing protocols such as STOMP, MQTT, and so on.
    • Many Clients
      • RabbitMQ supports almost all common languages, such as Java,.net, Ruby, and so on.
    • Management UI
      • RabbitMQ provides an easy-to-use user interface that enables users to monitor and manage many aspects of the message Broker.
    • Tracing mechanism
      • If a message is abnormal, RabbitMQ provides a message tracing mechanism so that the user can find out what happened.
    • Plugin System
      • RabbitMQ provides a number of plugins to extend it in many ways, or you can write your own plugins.
  • The concept is a bit of a mystery, so let’s start our RabbitMQ learning journey with the simplest model

Simple queue mode (point-to-point mode)

  • Create a new Maven project with the following directory structure

  • Pom import the jar

    • <! <plugins> <plugins> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>8</source>
                          <target>8</target> </configuration> </plugin> </plugins> </build> <dependencies> <! <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>5.8. 0</version> </dependency> <! <groupId> Commons - IO </groupId> <artifactId> Commons - IO </artifactId> <version>2.6</version>
              </dependency>
          </dependencies>
      Copy the code

    I. Producers

    • package com.dy.producer;
      
      import com.rabbitmq.client.Channel;
      import com.rabbitmq.client.Connection;
      import com.rabbitmq.client.ConnectionFactory;
      
      /** * This is a test producer *@author DingYongJun
       *@date2021/8/1 * /
      public class DyProducerTest_01 {
          public static final String Queue_name = "dayu";
      
          /** * For convenience, we use the main function to test *@param args
           */
          public static void main(String[] args) throws Exception{
              // Create a connection factory
              ConnectionFactory factory = new ConnectionFactory();
              factory.setHost("120.48.29.41");
              factory.setUsername("admin");
              factory.setPassword("111111");
      
              // Create a new connection
              Connection connection = factory.newConnection();
              // Create a channel that automatically closes an interface without displaying close
              Channel channel = connection.createChannel();
      
              /** * generate a queue * 1. Queue name * 2. Whether messages in the queue are persistent * 3. Is the queue only for one consumer to consume is it shared true Multiple consumers can consume * 4. Indicates whether the queue is automatically deleted after the last consumer disconnect. True Indicates whether the queue is automatically deleted * 5. Other parameters */
              channel.queueDeclare(Queue_name,false.false.false.null);
              String message="I'm the producer, and I've got good news for you!";
      
              /** * send a message * 1. Send to the switch * 2. What is the key of the route * 3. Other parameter information * 4. Body of the sent message */
              channel.basicPublish("",Queue_name,null,message.getBytes());
              System.out.println("Message sent."); }}Copy the code
    • Let’s do this and see if we can successfully get the message to the queue

    • View the RabbitMQ management page

    • Prove that the producer established successfully and successfully sent the message.

Ii. Consumers

  • package com.dy.consumer;
    
    import com.rabbitmq.client.*;
    
    /** * This is a test for consumers *@author DingYongJun
     *@date2021/8/1 * /
    public class DyConsumerTest_01 {
        public static final String Queue_name = "dayu";
    
        public static void main(String[] args) throws Exception{
            // Create a connection factory
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("120.48.29.41");
            factory.setUsername("admin");
            factory.setPassword("111111");
    
            // Establish the connection
            Connection connection = factory.newConnection();
            // Establish the channel
            Channel channel = connection.createChannel();
    
            System.out.println("I am the consumer, I am waiting to receive the message!");
            DeliverCallback deliverCallback = (String var1, Delivery var2)->{
                String message= new String(var2.getBody());
                System.out.println(message);
            };
            CancelCallback cancelCallback = (String var1)->{
                System.out.println("Message consumption interrupted");
            };
    
            /** * Consumer message * 1. Which queue to consume * 2. Whether to automatically reply after the consumption is successful true means automatic reply false manual reply * 3. A pullback where consumers failed to spend */
            channel.basicConsume(Queue_name,true,deliverCallback,cancelCallback); }}Copy the code
  • Explain, DeliverCallback and CancelCallback

    • Let’s see what parameters we need

    • Take a look at DeliverCallback, which is typically a functional interface, so we can use a LAMda expression to create its object.

      • import java.io.IOException;
        
        @FunctionalInterface
        public interface DeliverCallback {
            void handle(String var1, Delivery var2) throws IOException;
        }
        Copy the code
    • CancelCallback similarly

      • import java.io.IOException;
        
        @FunctionalInterface
        public interface CancelCallback {
            void handle(String var1) throws IOException;
        }
        Copy the code
  • Perform a consumer to see if you can get a message from the specified queue.

    • Successful consumption messages.
  • View the RabbitMQ management page

    • A message of zero proves that the message was successfully consumed!

Third, summary

  • The simplest work queue, with a message producer, a message consumer, and a queue. Also known as point-to-point mode.

  • General steps of producer

    • Get connected
    • Create channels
    • Create queue Declaration
    • Send a message
    • Close the queue
  • General consumer steps

    • Get connected
    • Access to the channel
    • Listening to the queue
    • News consumption
  • So, after looking at this simple queue pattern, you have a basic understanding of publish and subscribe mq.


I see no ending, but I will search high and low

If you think I blogger writes good! Writing is not easy, please like, follow, comment to encourage the blogger ~hahah