RabbitMQ notes - getting started

Keywords: RabbitMQ Java Erlang Session

Rabbitmq is a popular open source message queuing system, which is developed in erlang. The default port number is 5672, while the default port number of its background management system is 15672. The content of this blog post is an entry program used by rabbitmq, including message producers and consumers. The producers push messages to message queues, and then consumers listen to the queues and consume this message.

I. write producer code

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * rabbitmq Starter producer
 * @author sea
 * @date 20190714
 */
public class ProducerOne {
    // queue
    private static final String QUEUE = "hello_rabbit";
    // rabbitmq address
    private static final String HOST = "127.0.0.1";
    // port
    private static final int PORT = 5672;
    // username
    private static final String USERNAME = "guest";
    // passowrd
    private static final String PASSOWRD = "guest";

    public static void main(String[] args) {
        // Create a new connection through the connection factory and establish a connection with mq
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(HOST);
        connectionFactory.setPort(PORT);
        connectionFactory.setUsername(USERNAME);
        connectionFactory.setPassword(PASSOWRD);
        // Set virtual machines. A mq service can set multiple virtual machines. Each virtual machine is equivalent to an independent mq
        connectionFactory.setVirtualHost("/");
        Connection connection = null;
        Channel channel = null;
        try {
            // 1. Establish a new connection
            connection = connectionFactory.newConnection();
            // 2. Create a session channel. All communication between the producer and mq service is completed in the channel channel.
            channel = connection.createChannel();
            // 3. Declare the queue. If the queue does not exist in mq, create
            /**
             * Declaration queue
             * 1.Queue name
             * 2.Is it persistent? If persistent, the queue still exists after mq restarts.
             * 3.If the connection is closed, the queue will be deleted automatically. If it is set to true, it can be used to create a temporary queue.
             * 4.Auto delete: whether to delete the queue automatically when it is no longer in use. If set to true, it can be used to create a temporary queue.
             * 5.Queue parameters, extended parameters
             */
            channel.queueDeclare(QUEUE, true, false, false, null);
            // 4. Publish news
            /**
             * Message publishing method
             * param1: Exchange "If not specified, use Default Exchange (set to" ")"
             * param2:routingKey,The routing Key of the message, which is used by Exchange to forward the message to the specified message queue
             * param3:Properties contained in message
             * param4: Message body
             */
            String message = "This is hello rabbit message";
            channel.basicPublish("", QUEUE, null, message.getBytes());
            System.out.println("publish success");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } finally {
            try {
                // Close channel
                channel.close();
                // Close connection
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        }
    }
}

II. Write consumer code

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * rabbitmq Starter consumer
 * @author sea
 * @date 20190714
 */
public class ConsumerOne {
    // queue
    private static final String QUEUE = "hello_rabbit";
    // rabbitmq address
    private static final String HOST = "127.0.0.1";
    // port
    private static final int PORT = 5672;

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        //Set the ip and port of the server where MabbitMQ is located
        factory.setHost(HOST);
        factory.setPort(PORT);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //Define consumption method
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            /**
             * Consumer receives message call this method
             * @param consumerTag The label of the consumer, used to represent the consumer, is specified in channel.basicConsume().
             * @param envelope The content of the message package, from which the message id, message routingkey, switch, message and retransmission flag can be obtained
            (Need to resend after receiving message failure)
             * @param properties attribute
             * @param body Message content
             * @throws IOException
             * */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
                    throws IOException {
                //Switch
                String exchange = envelope.getExchange();
                System.out.println("exchange:" + exchange);
                //Routing key
                String routingKey = envelope.getRoutingKey();
                System.out.println("routingKey:" + routingKey);
                //Message id
                long deliveryTag = envelope.getDeliveryTag();
                System.out.println("deliveryTag:" +deliveryTag);
                //Message content
                String msg = new String(body,"utf-8");
                System.out.println("receive message:" + msg);
            }
        };
        /**
         * Listening queue String queue, boolean autoAck,Consumer callback
         * parameter
         * 1,Listening queue name
         * 2,Whether to reply automatically. If it is set to true, it means that the message has been automatically replied to mq when it is received. If mq receives the reply, it will delete the message. Set
         If false, you need to reply manually.
         * 3,The method of consuming messages is called by consumers after receiving messages.
         */
        channel.basicConsume(QUEUE, true, consumer);
    }
}

III. running producer program

First you need a rabbitmq that you can connect to.

Run the main method in ProducerOne.

The queue name I set in the code is:

private static final String QUEUE = "hello_rabbit";

After running the producer's program, you can view it in the Queues column of RabbitMQ Management. The list shows the current queue, as shown in the following figure:

IV. running consumer programs

Run the main method of ProducerOne. After the code on the consumer side is started, it will be in a listening queue state. As long as the queue has producers sending messages, consumers can consume messages, as shown in the following figure:

View the corresponding message in RabbitMQ Management, and the value of the Ready column changes to 0.

Posted by nlhowell on Fri, 25 Oct 2019 10:33:08 -0700