Use Java to simulate how consumers consume messages in rabbitMQ message queue

Keywords: Java RabbitMQ Distribution message queue

Use Java to simulate how consumers consume messages in rabbitMQ message queue

introduce

General summary: the producer produces a message and stores it in the message queue in rabbitmq, and then the consumer takes the message out of the message queue.

In this part of this tutorial, we will write two programs in Java. The producer who sends a single message and the consumer who receives and prints the message.

In the figure below, "P" is our producer and "C" is our consumer. The middle box is a queue - RabbitMQ represents the message buffer reserved by the consumer.

Introducing rabbitmq dependency

<dependencies>
        <!--rabbitmq Dependent client-->
        <dependency>
            <groupId>com.rabbitmq</groupId>
            <artifactId>amqp-client</artifactId>
            <version>5.8.0</version>
        </dependency>

        <!--A dependency on the operation file stream-->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>

    </dependencies>

    <!--to maven appoint jdk Compiled version-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

The producer sends the message to rabbitmq's message queue

If the consumer wants to use the message in the message queue, first we need to send the message to the message queue, and the producer mainly does this work. Here is the producer code, as follows:

/**
 * @Date 2021/11/8 19:44
 * @Author WangXuan
 * Producer: mainly used to send messages
 */
public class Producer {
    //Queue name
    public static final String QUEUE_NAME = "hello";

    //Send a message
    public static void main(String[] args) throws IOException, TimeoutException {
        //Create a connection factory, which actually corresponds to our access http://182.92.210.39:15672/ rabbitmq after the website can get the queue from this factory
        ConnectionFactory factory = new ConnectionFactory();

        //Queue of factory IP connection RabbitMQ
        factory.setHost("182.92.210.39");
        //user name
        factory.setUsername("admin");
        //password
        factory.setPassword("admin");

        //Create connection
        Connection connection = factory.newConnection();
        //Get the channel through which you can connect to the Exchange switch and then to the Queue
        Channel channel = connection.createChannel();

        /**
         * Generate a queue in which messages can be stored
         *
         * 1.Queue name
         * 2.Whether the messages in the queue are persisted to disk
         * 3.Whether the message queue is shared. true indicates that multiple consumers can access the message queue, and false indicates that only one consumer can access the message queue
         * 4.Whether to delete automatically. Whether to delete the message queue automatically after the last consumer disconnects
         * 5.Other parameters
         * */
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        //Messages to be sent to the hello queue
        String message = "hello world";

        /**
         * Send a message to the queue
         *
         * 1.To which switch
         * 2.What is the Key value of the route? This is the name of the queue
         * 3.Other parameter information
         * 4.The message body of the sending message needs to be converted into a Byte array
         * */
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());

        //If the message is successfully sent to the hello queue, this code will be output
        System.out.println("Message sent");
    }
}


When the producer produces a message and sends it to the message queue, an exception will appear, as shown in the following figure:

Re run, as shown in the following figure:

Consumer fetches message from message queue

The consumer's code is as follows:

/**
 * @Date 2021/11/9 17:31
 * @Author WangXuan
 *
 * Consumer receives message
 */
public class Consumer {
    //Which queue does the consumer want to get messages from
    public static final String QUEUE_NAME="hello";

    public static void main(String[] args) throws IOException, TimeoutException {
        //Create connection factory
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("182.92.210.39");
        //user name
        factory.setUsername("admin");
        //password
        factory.setPassword("admin");

        Connection connection = factory.newConnection();

        Channel channel = connection.createChannel();

        //The callback function that will be called if the message is successfully received
        DeliverCallback deliverCallback=(consumerTag,message)->{
            System.out.println(new String(message.getBody()));
        };

        //The callback function that will be called if you cancel getting a message from the message queue
        CancelCallback cancelCallback=consumerTag->{
            System.out.println("Message consumption interrupted");
        };

        /**
         *  Consumers consume messages, that is, consumers get messages from the message queue
         *
         *  1.Which queue to consume
         *  2.Whether to respond automatically after successful consumption. true means automatic response, and false means manual response
         *  3.Callback of successful consumption by consumers
         *  4.Consumer cancels the callback of consumption
         * */
        channel.basicConsume(QUEUE_NAME,true,deliverCallback,cancelCallback);
    }
}

Start sequence

Start the consumer first, as shown in the following figure:

Then start the producer, as shown in the following figure:

At this time, go to the consumer service and find that the consumer has successfully obtained messages from the message queue of rabbitmq, as shown in the following figure:

The meaning of connection, channel and queue in the code

See the figure below:

Where did the producer send the message?

The producer sends the message to the rabbitMQ message queue in its linux remote server, as shown in the following figure:

Therefore, when we use consumers to fetch messages from the message queue, the first step must be to connect to the rabbitMQ message queue in our remote server.

Posted by ashii on Tue, 09 Nov 2021 15:11:05 -0800