The core concepts of RabbitMQ, you must understand!

Java technology stack

www.javastack.cn

Follow to read more quality articles

Author: Sea to
Source: cnblogs.com/haixiang/p/10853467.html

RabbitMQ features

Compared with other message queues, RabbitMQ has a series of measures to prevent message loss and has powerful high availability performance. Its throughput may not be as large as other message queues, but its message security is outstanding and is widely used in financial services.

AMQP protocol

AMQP: Advanced Message Queuing Protocol

AMQP definition: It is a binary protocol with modern characteristics. It is an application layer standard advanced message queuing protocol that provides unified messaging services. It is an open standard for application layer protocols and is designed for message-oriented middleware.

The Erlang language was originally based on the architectural model of the switch field, which made the performance of RabbitMQ's data exchange between Brokers very good. The advantages of Erlang: Erlang has the same delay as native Socket.

RabbitMQ is an open source message broker and queue server, used to share data between completely different applications through common protocols. RabbitMQ is written in Erlang language, and RabbitMQ is based on AMQP protocol. Follow the public number Java technology stack to get a series of RabbitMQ tutorials.

RabbitMQ messaging mechanism

The producer sends the message to the specified Exchange, and the Exchange sends the message to 0-n queues according to the routing key according to its own type (direct, topic, etc.), and then the queue forwards the message to the consumer.

Server: also known as Broker, accepts client connections and implements AMQP entity services, here refers toRabbitMQ 服务器

Connection: Connection, the application is connected to the Broker's network.

Channel: Network channel. Almost all operations are performed in Channel. Channel is the channel for reading and writing messages. The client can create multiple Channels: each Channel represents a session task.

Virtual host: Virtual address, used for logical isolation, is the top message routing. There can be several Exchanges and Queues in a Virtual Host, and there cannot be Exchange or Queues with the same name in the same VirtualHost. The smallest granularity of permission control is Virtual Host.

Binding: Virtual connection between Exchange and Queue. The binding can contain routing key.

Routing key: A routing rule that the virtual machine can use to determine how to route a specific message, that is, the key that the switch binds to the Queue.

Queue: Also known as Message Queue, message queue, save messages and forward them to consumers.

Message

The message, the data transmitted between the server and the application, is composed of Properties and Body. Properties can modify the message, such as the message priority, delay and other advanced features; Body is the content of the message body.

In properties, we can set the message expiration time and whether to persist, etc., or pass in custom map properties, which can also be obtained on the consumer side.

Producer

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.util.HashMap;
import java.util.Map;

public class MessageProducer {
    public static void main(String[] args) throws Exception {
        //1. 创建一个 ConnectionFactory 并进行设置
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setVirtualHost("/");
        factory.setUsername("guest");
        factory.setPassword("guest");

        //2. 通过连接工厂来创建连接
        Connection connection = factory.newConnection();

        //3. 通过 Connection 来创建 Channel
        Channel channel = connection.createChannel();

        //4. 声明 使用默认交换机 以队列名作为 routing key
        String queueName = "msg_queue";

        /**
         * deliverMode 设置为 2 的时候代表持久化消息
         * expiration 意思是设置消息的有效期,超过10秒没有被消费者接收后会被自动删除
         * headers 自定义的一些属性
         * */
        //5. 发送
        Map<String, Object> headers = new HashMap<String, Object>();
        headers.put("myhead1", "111");
        headers.put("myhead2", "222");

        AMQP.BasicProperties properties = new AMQP.BasicProperties().builder()
                .deliveryMode(2)
                .contentEncoding("UTF-8")
                .expiration("100000")
                .headers(headers)
                .build();
        String msg = "test message";
        channel.basicPublish("", queueName, properties, msg.getBytes());
        System.out.println("Send message : " + msg);

        //6. 关闭连接
        channel.close();
        connection.close();

    }
}

consumer

import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.Map;

public class MessageConsumer {
    public static void main(String[] args) throws Exception{
        //1. 创建一个 ConnectionFactory 并进行设置
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setVirtualHost("/");
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setAutomaticRecoveryEnabled(true);
        factory.setNetworkRecoveryInterval(3000);

        //2. 通过连接工厂来创建连接
        Connection connection = factory.newConnection();

        //3. 通过 Connection 来创建 Channel
        Channel channel = connection.createChannel();

        //4. 声明
        String queueName = "msg_queue";
        channel.queueDeclare(queueName, false, false, false, null);

        //5. 创建消费者并接收消息
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body)
                    throws IOException {
                String message = new String(body, "UTF-8");
                Map<String, Object> headers = properties.getHeaders();
                System.out.println("head: " + headers.get("myhead1"));
                System.out.println(" [x] Received '" + message + "'");
                System.out.println("expiration : "+ properties.getExpiration());
            }
        };

        //6. 设置 Channel 消费者绑定队列
        channel.basicConsume(queueName, true, consumer);
    }
}
Send message : test message

head: 111
 [x] Received 'test message'
100000

Exchange

1 Introduction

Exchange is a switch that receives messages and forwards them to the bound queue according to the routing key. Many messages enter the Exchange, and Exchange distributes the messages to different Queues according to the Routing key.

2. Type

There are many types of Exchange in RabbitMQ . Different types have different message distribution mechanisms, as follows:

  • fanout: Broadcast mode. This type of Exchange will distribute the Message to all Queues bound to the Exchange.

  • direct: This type of Exchange will distribute the Message to the specified Queue according to the Routing key (exact match).

  • Topic: This type of Exchange will distribute the Message to the specified Queue according to the Routing key (fuzzy matching).

  • headers: The theme switch is similar, but the route different from the theme switch is based on the routing key, and the routing value of the header switch is based on the header data of the message. The subject switch routing key can only be a string, while the head switch can be an integer and a hash value.

3. Properties

/**
* Declare an exchange, via an interface that allows the complete set of
* arguments.
* @see com.rabbitmq.client.AMQP.Exchange.Declare
* @see com.rabbitmq.client.AMQP.Exchange.DeclareOk
* @param exchange the name of the exchange
* @param type the exchange type
* @param durable true if we are declaring a durable exchange (the exchange will survive a server restart)
* @param autoDelete true if the server should delete the exchange when it is no longer in use
* @param internal true if the exchange is internal, i.e. can't be directly
* published to by a client.
* @param arguments other properties (construction arguments) for the exchange
* @return a declaration-confirm method to indicate the exchange was successfully declared
* @throws java.io.IOException if an error is encountered
*/
Exchange.DeclareOk exchangeDeclare(String exchange,
                                 String type,boolean durable,
                                 boolean autoDelete,boolean internal,
                                 Map<String, Object> arguments) throws IOException;
  • Name: Switch name

  • Type: Switch type direct, topic, fanout, headers

  • Durability: Do you need persistence, true means persistence

  • Auto Delete: When the last queue bound to Exchange is deleted, the Exchange will be deleted automatically

  • Internal: Whether the current Exchange is used internally by RabbitMQ, the default is False

  • Arguments: extended parameters, used to extend AMQP protocol self-defined use

Recent hot articles:

1. I wrote a piece of logic in Java 8, but my colleagues couldn't understand it directly

2. Spring Boot study notes, this is too complete!

3. Hang Tomcat, Undertow performance is very explosive! !

4. Spring Boot is too cruel, release 3 versions at a time!

5. How does Spring Boot integrate Redis quickly?

6、The latest release of "Java Development Manual (Songshan Edition)"

7. Spring Boot Redis implements distributed locks, which is so fragrant!

8. Chinese open sourced a small and complete Java tool library !

9. The Chinese open sourced a super easy to use Redis client! !

10、My colleague wrote a hidden bug, and I checked it for 3 days!

Scan the QR code to follow the official account of the Java Technology Stack to read more dry goods.

Click " Read Original " to get a complete list of interview questions~

Guess you like

Origin blog.csdn.net/youanyyou/article/details/108459356
Recommended