RabbitMQ entry describes the installation and use

A, RabbitMQ acquaintance

RabbitMQ is an implementation of the Advanced Message Queuing Protocol (AMQP message broker (also known as message-oriented middleware), it accepts and forwards messages. It can help you deal with some of the logic of the transaction, thereby decoupling, such as user registration database after the fall, also you need to send mail authentication is required to send the couple a red envelope, and so on things, you can do it to the middleware also can use it as a post office: when you want to mail letters, you will deliver the letter in the box, and postman will eventually make sure the letter to the hands of the recipient. in this example, it is comparable to RabbitMQ drop box, the post office and the postman.

1.1 AMQP protocol

AMQP, namely Advanced Message Queuing Protocol, to provide a unified messaging service application layer standard Advanced Message Queuing Protocol, is an open standard application layer protocol for message-oriented middleware design. Based on this protocol client and messaging middleware message can be transmitted, is not subject to the limitations of the client / middleware products, different development language.

1.2 Typical application scenarios

  1. Cross-system asynchronous communication, asynchronous, decoupled, clipping.
  2. Synchronization becomes asynchronous spike in applications: Send ourselves
  3. Event based Pub / Sub model implementation driving abandon ELT (such as the total amount of data synchronization merchant); abandon API (such as the timing of acquiring the incremental users get product into incremental broadcast).
  4. The final consistency achieved using the RabbitMQ affairs

1.3 RabbitMQ features

RabbitMQ using Erlang language, use Mnesia database to store messages.

  1. Reliability (Reliability) RabbitMQ use some mechanism to ensure the reliability, such as persistence, transmission confirmation, confirm the release.
  2. Flexible Routing (Flexible Routing) before entering the message queue, the message is routed through the Exchange. For a typical routing function, RabbitMQ has provided some built-in Exchange to achieve. For more sophisticated routing capabilities, multiple Exchange can bind together, but also realize their Exchange through a plug-in mechanism.
  3. Cluster message (Clustering) may be composed of a plurality of RabbitMQ cluster servers form a logical Broker.
  4. HA (Highly Available Queues) queues may be mirrored on the machines in the cluster, such that in case of partial node according to the
    queue is still available.
  5. Multiple protocols (Multi-protocol) RabbitMQ message queue supports multiple protocols, such as AMQP, STOMP, MQTT like.
  6. Multi-language client (Many Clients) RabbitMQ supports almost all commonly used languages, such as Java, .NET, Ruby, PHP, C #, JavaScript, and so on.
  7. Management Interface (Management UI) RabbitMQ provides an easy to use user interface, enabling users to monitor and manage messages, the cluster nodes.
  8. Plug-in mechanism (Plugin System) RabbitMQ provides a number of plug-ins to achieve expansion in many ways, of course, you can also write your own plug-ins.

1.4 working model

Here Insert Picture Description

  1. Broker
    we want to use RabbitMQ to send and receive messages, RabbitMQ have to install a service that can be installed on top of Windows can also be installed on top of Linux, the default is port 5672. This RabbitMQ server we call it Broker, MQ server things we do is to help storing, forwarding messages.
  2. Connection
    whether producers send messages, receive messages or consumers, must keep up a connection between the Broker, this connection is a TCP long connection.
  3. Channel
    if all producers and consumers to send messages to receive messages directly create and release words long TCP connections for Broker who will certainly cause a great loss of performance, because the TCP connection is a very valuable resource, but also the creation and release to consume time. So AMQP which introduced the concept of the Channel, it is a virtual connection. We translate it into the channel, or message channel. So that we can maintain long TCP connections inside to create and release the Channel, greatly reduce the consumption of resources. Another thing to note is that, Channel RabbitMQ native API is inside the most important programming interface, which means that we define switches, queue, binding relationship, send a message consumer news, on Channel interfaces are method calls.
  4. Queue
    In other MQ inside the ActiveMQ example, messages are sent to the queue. Queue is used to store the real message, the process is a stand-alone with its own database. Consumers get a message There are two modes, one is Push mode, as long as the producer to the server, immediately pushed to the consumer. The other is the Pull mode, the message is stored on the server, only to get consumers to take the initiative to get the message. Consumers need to write a while loop continue to get messages from the queue it? No, we can based on the event mechanism, the consumer listens to the queue.
    Since the FIFO queue has the characteristics of, after the consumer receives a message is, this message will be deleted from the database before only determined to continue to deliver the next message.
  5. Exchange
    never appear inside the RabbitMQ message directly to the queue's. Since the introduction of the concept of a switch (Exchange) in which AMQP used to achieve flexible routing messages.
    Switch is a list of bindings, used to find the matching binding relationship. Queue using the key bindings (Binding Key) establishing a binding relationship with the switch. Producers need to carry the message sent by the routing key (Routing Key), based on the binding list save it, the decision on which route the message to the queue when it is bound to switch receives the message. Note: switches and queue, queue-many relationship with the consumers are.
  6. Vhost
    each we need to implement, we need to use to create their own switches on the server system based on asynchronous communication RabbitMQ, queues and their binding relationship. If a business system do not want to mix a system with others, how to do? Then purchase a separate server hardware to install a RabbitMQ service? In this way the cost is too high. Install multiple RabbitMQ service it on the same server hardware? For example, run a port of 5673?
    It is not necessary, because RabbitMQ provides a virtual host VHOST. VHOST addition to the improved utilization of hardware resources, you can also achieve the control and authority of the quarantine resources. Its role is similar to the namespace and programming language package, different VHOST can have the same name and Exchange Queue, they are completely transparent.
    This time, we can create different user (User) for the different business systems, and then assign permissions VHOST to these users. The user permissions VHOST air distribution control system such as control system to the wind, the user can access the inside of the switch and queues. Super administrator to assign permissions to all of VHOST. RabbitMQ we talk about introducing Exchange in order to achieve flexible routing messages, which in the end routing?
  7. Producer Manufacturer: mainly delivers messages corresponding to the above Exchange. General is an independent program.
  8. Consumer Consumers: recipient of the message, typically stand-alone program.

1.5 Three main switch

1.5.1 Direct Exchange Direct Switch

Definition: Direct Connect type of switch with a queue bindings, you need to specify an explicit binding key.
Routing rules: send a message directly connected to the type of switch, the only routing key binding key with exact match, bound queue to receive messages.
Here Insert Picture Description

E.g:

 // 只有队列1能收到消息
channel.basicPublish("MY_DIRECT_EXCHANGE", "key1", null, msg.getBytes());

1.5.2 Topic Exchange theme switch

Definition: subject type switch with a queue binding routing key can be specified by the pattern matching.
There are two wildcards, * represents a matching word. On behalf of # Match zero or more words. Separated by. Between words.
Routing rule: When sending a message to the topic type of switches, routing key accord binding key patterns, bound queue to receive messages.
Here Insert Picture Description
E.g:

 // 只有队列1能收到消息
channel.basicPublish("MY_TOPIC_EXCHANGE", "ab.123", null, msg.getBytes());
// 队列2和队列3能收到消息
channel.basicPublish("MY_TOPIC_EXCHANGE", "bc.abc", null, msg.getBytes());

1.5.2 Fanout Exchange Broadcast switch

Definition: The broadcast type switch and a queue bound, do not need to specify the binding key.
Routing Rule: When a broadcast message is sent to the types of switches, do not need to specify the routing key, all of it is bound can receive message queue.
Here Insert Picture Description
E.g:

 // 3个队列都会收到消息
channel.basicPublish("MY_FANOUT_EXCHANGE", "", null, msg.getBytes());

Second, install and run

2.1 windows and linux systems

Direct official website to download the archive, extract to, sbin directory to start rabbitmq-server can be.

2.2 mac

mac system can also download the installation package, I am with homebrew installed.

brew install rabbitmq

After the installation will start command.

# 启动
$ brew services start rabbitmq

# 重启
$ brew services restart rabbitmq

# 停止
$ brew services stop rabbitmq

Start complete access http://localhost:15672/#/. See the following page is installed successfully.
Here Insert Picture Description
Account password are guest. Do not enter. Direct login on the line.

Third, the production of simple consumer examples

First introduced pom dependency. Based on the springboot.

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-amqp</artifactId>
		</dependency>

3.1 Producer

package com.example.demo;

/**
 * @author : pengweiwei
 * @date : 2020/1/29 7:09 下午
 */

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

import java.util.Map;

public class MyProducer {
    private final static String QUEUE_NAME = "ORIGIN_QUEUE";

    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        // 连接IP
        factory.setHost("127.0.0.1");
        // 连接端口
        factory.setPort(5672);
        // 虚拟机
        factory.setVirtualHost("/");
        factory.setUsername("guest");
        factory.setPassword("guest");
        // 建立连接
        Connection conn = factory.newConnection();
        // 创建消息通道
        Channel channel = conn.createChannel();

        String msg = "Hello, RabbitMQ";
        // 声明队列
        /**
         * 第一个参数:String queue
         * 第二个参数:boolean durable
         * 第三个参数:boolean exclusive,
         * 第四个参数:boolean autoDelete
         * 第五个参数:Map<String, Object> arguments
         */
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        // 发送消息(发送到默认交换机AMQP Default,Direct) 如果有一个队列名称跟Routing Key相等,那么消息会路由到这个队列

        /**
         * 第一个参数:String exchange
         * 第二个参数:String routingKey
         * 第三个参数:BasicProperties props
         * 第四个参数:byte[] body
         */
        channel.basicPublish("", QUEUE_NAME, null, msg.getBytes());
        channel.close();
        conn.close();
    }
}

3.2 Consumers

package com.example.demo;

/**
 * @author : pengweiwei
 * @date : 2020/1/29 7:09 下午
 */

import com.rabbitmq.client.*;

import java.io.IOException;

public class MyConsumer {
    private final static String QUEUE_NAME = "ORIGIN_QUEUE";

    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory(); 
        // 连接IP
        factory.setHost("127.0.0.1");
        // 默认监听端口
        factory.setPort(5672);
        // 虚拟机
        factory.setVirtualHost("/");
        // 设置访问的用户
        factory.setUsername("guest");
        factory.setPassword("guest");
        // 建立连接
        Connection conn = factory.newConnection();
        // 创建消息通道
        Channel channel = conn.createChannel();
        /**
         * 声明队列
         * 第一个参数:String queue
         * 第二个参数:boolean durable
         * 第三个参数:boolean exclusive,
         * 第四个参数:boolean autoDelete
         * 第五个参数:Map<String, Object> arguments
         */
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println(" Waiting for message....");
        // 创建消费者
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, "UTF-8");
                System.out.println("Received message : '" + msg + "'");
            }
        };
        /**
         * 开始获取消息
         * 第一个参数:String queue
         * 第二个参数:boolean autoAck
         * 第三个参数:Consumer callback
         */
        channel.basicConsume(QUEUE_NAME, true, consumer);
    }
}

2.3 operating results

Here Insert Picture Description

2.4 Parameter Description

Parameter declaration Switch

String type:交换机的类型,direct, topic, fanout中的一种。
boolean durable:是否持久化,代表交换机在服务器重启后是否还存在。

Parameter declaration queue

boolean durable:是否持久化,代表队列在服务器重启后是否还存在。
boolean exclusive:是否排他性队列。排他性队列只能在声明它的Connection中使用,连接断开时自动删除。
boolean autoDelete:是否自动删除。如果为true,至少有一个消费者连接到这个队列,之后所有与这个队列连接 的消费者
都断开时,队列会自动删除。
Map<String, Object> arguments:队列的其他属性。含义详细见下表。
Attributes meaning
x-message-ttl Survival time of messages in the queue, in milliseconds
x-expires How long has it been in the queue will be deleted after consumers access
x-max-length The maximum number of message queue
x-max-length-bytes The maximum capacity of the queue, the unit Byte
x-dead-letter-exchange Dead Letter Queue Switch
x-dead-letter-routing-key Dead Letter routing switch key
x-max-priority It can not exceed the maximum priority of the priority of the message in the message queue

Message Properties BasicProperties
main parameters:

parameter DEFINITIONS
Map<String,Object> headers Other custom parameters message
Integer deliveryModel Persistence, Other: transient
Integer priority Priority of the message
String correlationId Association ID, to facilitate RPC requests associated with the corresponding
String replyTo Callback queue
String expiration TTL Message expiration time, in milliseconds
Published 51 original articles · won praise 12 · views 50000 +

Guess you like

Origin blog.csdn.net/weiwei_six/article/details/104108709