The most worthy to show off in one’s life should not be how much you have wealth (although this is a bit against my heart, ha ha), but your ability to learn. The speed of technological innovation is very fast, so as programmers, we should have a heart to embrace change and actively follow up.

Prior to RabbitMQ, I had learned about Redis, Elasticsearch, and MongoDB, which made me feel very geeky and good.

Before I go on, I must say that I have not studied RabbitMQ very deeply, just to learn how to use it. But as a responsible tech blogger, I was tempted, and this tutorial will be so satisfying that you can’t help liking it mercilessly and retweeting it outright.

Of course, friends encounter mistakes in the article, don’t be lenient, can group to beat me, but make sure that one point, don’t hit the face, I am afraid of disfigurement.

01. What is RabbitMQ

First of all, I know that Rabbit is a Rabbit, and the cute image has popped into my mind. So what is MQ? RabbitMQ is an acronym for Message Queue, meaning RabbitMQ is an open source Message Queue system.

RabbitMQ’s key features are robustness, ease of use, high performance, high concurrency, easy cluster scaling, and strong open source community support. I mean, it looks like it’s awesome.

Nine years ago, when I was doing bulk futures trading, I also needed message push. At that time, I didn’t know how to find such off-the-shelf middleware, so I used custom queues to implement it. As a result, I made a lot of bugs, some of which have not been solved yet.

The RabbitMQ message model is shown below.

1) P is Producer, representing Producer, i.e., the sender of messages, who can send messages to X

2) X stands for Exchange, which can accept messages sent by producers and route them to the specified queue

3) Q stands for Queue, which stores messages sent by the switch

4) C is a Consumer, which means the Consumer, the receiver of the message, gets the message from the queue

Does this make RabbitMQ very concrete? Learn, boys and girls!

02. Install Erlang

Install RabbitMQ. First, the official explanation.

I don’t understand English very well, it doesn’t matter, I will add two words. The RabbitMQ server is written in Erlang and does not have an Erlang integrated environment in its installation package, so you will need to install Erlang first. Don’t worry, Erlang is easy to install.

Erlang download address:

Erlang.org/download/ot…

The latest version is 23.0.1, and I chose the 64-bit version, around 104M. Once you’ve downloaded it, you can double click to start the installation, dumb-ass.

Please note that during the installation process, my computer rebooted once, as if I wanted to install some library, I forgot to save the picture before restarting. After the restart, double-click the otp_win64_23.0.1.exe file to complete Erlang installation.

03. Install RabbitMQ

Once Erlang is installed, RabbitMQ can be installed. The download address is as follows:

www.rabbitmq.com/install-win…

Locate the location in the image below and select the file in the red box to download.

The installation package is only 16.5m in size and very lightweight. After downloading directly double-click to run the EXE file can be fool to install.

Once installed, RabbitMQ can be started as a Windows service and can be managed from the Start menu.

Click RabbitMQ Command Prompt (sbin dir) to go to the Command line and enter rabbitmqctl.bat status to check the RabbitMQ startup status.

You can see some state information for RabbitMQ:

  • The process ID, or PID, is 2816
  • The operating system is Windows
  • The current version is 3.8.4
  • Erlang configuration information

The command line interface doesn’t look elegant, so we can type the following command to enable the client administration UI plug-in:

rabbitmq-plugins enable rabbitmq_management
Copy the code

The following information confirms that the plug-in has been successfully enabled.

Enter http://localhost:15672/ in the browser address bar to enter the management interface, as shown below:

04. Use RabbitMQ in Java

Some people may ask, “I’m a Java programmer, how do I use RabbitMQ in Java?” That’s a good question. I’m on my way. I’m on my way.

First, add RabbitMQ client dependencies to your project:

<dependency>
    <groupId>com.rabbitmq</groupId>
    <artifactId>amqp-client</artifactId>
    <version>5.9.0</version>
</dependency>
Copy the code

In the second step, we simulate the simplest scenario where a producer sends a message to a queue and a consumer reads the message from the queue and prints it.

There’s a good official explanation for RabbitMQ, so I’m going to use it. When I was in high school, the most popular way of communication among classmates was not QQ, wechat or even SMS, but letters. Since there were no smartphones in those days and phones were banned at school, letters were the best way to express your feelings. I miss it.

Suppose I write a love letter to my girlfriend, Alley, which reads as follows:

To the alley Hello, alley. I have been bored every day since you left, like Don Quixote, thinking of Dulcinea of Toboso. Now I have formed a habit, is every two or three days to ask you to say a few words do not want to say to others. . Wang Er, May 20th

Then this love letter to send to the alley, I need to run to the post office, buy stamps, drop in the mailbox. Girlfriend to receive this love letter, you need to do your best not to lose it.

RabbitMQ is like the post office, only instead of mail, it handles messages. So as we explained before, P is the producer, and C is the consumer.

Create producer class Wanger:

public class Wanger {
    private final static String QUEUE_NAME = "love";
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();

        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            channel.queueDeclare(QUEUE_NAME, false.false.false.null);
            String message = "Alley, I like you.";
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes(StandardCharsets.UTF_8));
            System.out.println("[King Ii] send '" + message + "'"); }}}Copy the code

QUEUE_NAME is the name of the queue, that is, messages sent by the producer will be placed in the love queue.

2) Create a server connection by:

ConnectionFactory factory = new ConnectionFactory();
try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
Copy the code

ConnectionFactory is a handy factory class that can be used to create a default connection to RabbitMQ (host name “localhost”). Then, create a Channel to send the message.

The Connection and Channel classes implement the Closeable interface, so you can use the try-with-resource statement. If you are not familiar with the try-with-resource statement, check out my previous article.

3) When sending messages, you must set the queue name, using the queueDeclare() method.

4) basicPublish() is used to publish messages:

  • The first argument is exchange, which is not required in the current scenario, so it is set to an empty string.
  • The second parameter is a routingKey, provisionally populated with the queue name;
  • The third parameter is the other parameters of the message (BasicProperties), which is not configured for now.
  • The fourth parameter is the body of the message, which is a byte array in UTF-8 format, effectively eliminating Chinese garbled characters.

Now that we have the producer class, create a new consumer class.

public class XiaoXiang {
    private final static String QUEUE_NAME = "love";
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME, false.false.false.null);
        System.out.println("Waiting to receive message");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println("Message received by [alley]" + message + "'");
        };
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { }); }}Copy the code

1) The code to create the channel is similar to that of the producer, except that we don’t use try-with-resource statements to automatically close the connection and channel, because we want the consumer to keep the connection until we force it to close.

2) When a message is received, the queue name must be set using the queueDeclare() method.

3) Since RabbitMQ will be pushing messages to us asynchronously, we need to provide a callback that will buffer the messages until we are ready to receive them.

DeliverCallback deliverCallback = (consumerTag, delivery) -> {
    String message = new String(delivery.getBody(), "UTF-8");
    System.out.println("Message received by [alley]" + message + "'");
};
Copy the code

The basicConsume() method is used to receive messages:

  • The first parameter is queue, which matches the producer (love).

  • The second parameter is autoAck, which, if true, indicates that the server delivers the message once. How do you understand this concept? You can run the producer class Wanger several times before running the consumer class XiaoXiang, and send multiple messages to the queue. When the consumer class is started, you will see multiple messages received at once, like the following.

Waiting for received message [alley] Received message'Alley, I like you. '[Alley] received message'Alley, I like you. '[Alley] received message'Alley, I like you. '
Copy the code
  • The third argument is DeliverCallback, which is the message’s callback function.

  • The fourth parameter is CancelCallback.

You can also use the RabbitMQ management panel to view the message graph during the message sending process, as shown below.

05, thanks

That’s the end of this article, so if you want to play RabbitMQ, get started! If you have any problems in the process of learning, please feel free to communicate with me. Although I am a rookie, I am enthusiastic.

Also, if you want to write an entry level article, this is the perfect example.

I am silent King 2, an interesting programmer. If you think this article is helpful to you, please search “Silent King ii” on wechat and read it for the first time. Reply [666] there is also a 500G HIGH-DEFINITION teaching video (classified) that I prepared for you.

Interview on GitHub

Original is not easy, do not want a free ticket, please point a praise for this article, it will be the strongest power FOR me to write more high-quality articles.