[RabbitMQ] A brief overview of RabbitMQ, usage and switch model

MQ overview:

Message Queue (message queue), a container that saves messages during the transmission of messages, is used for communication between distributed systems. There are
two ways of communicating in distributed systems: direct remote call and indirect communication with the help of third parties
. Called the producer, the receiver is called the consumer

MQ advantages and disadvantages

Advantage:

  1. Application decoupling: If you separate the different functions of a system and connect mq in the middle, then the system failure of one of the functions will not affect other systems, achieving decoupling.
  2. Asynchronous speed-up: If an order accepts an order request, it normally needs to go through the three systems of inventory, payment, and logistics. However, you can directly interact with mq and then return directly. Those three systems use mq to queue for operations, greatly shortening the waiting time. , increase system throughput
  3. peak shaving and valley filling

Disadvantages:

  1. Reduced system availability
  2. Increased system complexity
  3. Consistency issue

RabbitMQ is a middleware for software communication based on AMQP (Advanced Message Queuing Protocol)

RabbitMQ four cores

  1. producer
  2. consumer
  3. queue
  4. switch

The AMQP protocol is a binary protocol that defines a set of rules and standards to ensure that messages can be delivered and interpreted between different applications and platforms. AMQP contains four core components:

  1. information
  2. switch
  3. queue
  4. binding

working principle

Broker: An application that accepts and distributes messages. RabbitMQ Server is Message Broker
Virtual host: it is the concept of a virtual host. A Broker can have multiple Virtual hosts. Each Virtual has its own set of Exchange (switch) and Queue (queue).

How RabbitMQ works

Get started quickly

  1. Import dependencies
    <dependency>
      <groupId>com.rabbitmq</groupId>
      <artifactId>amqp-client</artifactId>
      <version>5.16.0</version>
    </dependency>
  1. write a producer
public class Producer {
    
    
    public static void main(String[] args) throws Exception {
    
    

        String queueName = "test_queue_name";
        String exchangeName = "test_exchange_name";
        //创建链接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //服务地址
        factory.setHost("xx.xx.xx.xx");
        //账号密码
        factory.setUsername("root");
        factory.setPassword("xxx");
        //端口号
        factory.setPort(5672);
        //创建链接
        Connection connection = factory.newConnection();
        //创建信道
        Channel channel = connection.createChannel();

        /**
         * 创建交换机
         * params:
         * 1. 交换机名称
         * 2. 交换机类型:direct,topic,fanout,headers
         * 3. 指定交换机是否持久化 - true:那么交换机的元数据要持久化
         * 4. 指定交换机没有队列绑定时是否需要删除
         * 5. Map<String,Object>用来指定我们交换机其他的结构化参数,
         */
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT,true,false,null);

        /**
         * 生成一个队列
         * params
         * 1. 队列名称
         * 2. 队列是否需要持久化 - 是队列名称等这些元数据的持久化,不是队列中消息的持久化
         * 3. 标识队列是不是私有的,如果是私有的,只有创建它的应用程序才能消费消息
         * 4. 队列在没有消费者订阅的情况下是否自动删除
         * 5. 队列的一些结构化信息,比如声明私信队列,磁盘队列会用到
         */
        channel.queueDeclare(queueName,true,false,false,null);

        /**
         * 将交换机和队列绑定
         * params:
         * 1.队列名称
         * 2. 交换机名称
         * 3. 路由键 - 在直连模式下,可以为我们队列名称
         */
        channel.queueBind(queueName,exchangeName,queueName);

        /**发送消息
         * params:
         * 1. 发送到哪个交换机
         * 2. 队列名称
         * 3. 其他参数信息
         * 4. 发送消息的消息体
         */
        String msg = "hello RabbitMQ!";
        channel.basicPublish(exchangeName,queueName,null,msg.getBytes());
        channel.close();
        connection.close();
    }
}
  1. Write another consumer to consume messages
public class Consumer {
    
    
    public static void main(String[] args) throws Exception{
    
    
        String queueName = "test_queue_name";
        String exchangeName = "test_exchange_name";
        //创建链接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //服务地址
        factory.setHost("xx.xx.xx.xx");
        //账号密码
        factory.setUsername("root");
        factory.setPassword("xxx");
        //端口号
        factory.setPort(5672);
        //创建链接
        Connection connection = factory.newConnection();
        //创建信道
        Channel channel = connection.createChannel();

        //接收消息的回调函数
        DeliverCallback deliverCallback = (consumerTage, message) -> {
    
    
            System.out.println("接收到消息" + new String(message.getBody()));
        };

        //取消消息的回调函数
        CancelCallback cancelCallback = consumerTage -> {
    
    
            System.out.println("消费消息被中断");
        };
        /**
         * 消费消息
         * Params:
         * 1. 消费那个队列
         * 2. 消费成功后是否自动应答
         * 3. 接收消息的回调函数
         * 4. 取消消息的回调函数
         */
        channel.basicConsume(queueName,true,deliverCallback,cancelCallback);
    }
}

RabbitMQ switch type

  1. The switch whose direct
    routing key exactly matches the queue name is bound to the switch and queue through the RoutingKey routing key.
public class Producer {
    
    
    public static void main(String[] args) throws Exception {
    
    



        String exchangeName = "test_exchange_name";
        String queueName1 = "test_queue_name1";
        String queueName2 = "test_queue_name2";
        String queueName3 = "test_queue_name3";
        String queueName4 = "test_queue_name4";

        String key1 = "key_1";
        String key3 = "key_3";
        String key4 = "key_4";

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("xx.xxx.xxx.xx");
        factory.setUsername("root");
        factory.setPassword("xxx");
        factory.setPort(5672);
        Connection connection = factory.newConnection();       
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT,true,false,null);

        channel.queueDeclare(queueName1,true,false,false,null);
        channel.queueDeclare(queueName2,true,false,false,null);
        channel.queueDeclare(queueName3,true,false,false,null);
        channel.queueDeclare(queueName4,true,false,false,null);

        channel.queueBind(queueName1,exchangeName,key1);
        channel.queueBind(queueName2,exchangeName,key1);
        channel.queueBind(queueName3,exchangeName,key3);
        channel.queueBind(queueName4,exchangeName,key4);

        channel.basicPublish(exchangeName,key1,null,"hello Key1".getBytes());
        channel.basicPublish(exchangeName,key3,null,"hello Key3".getBytes());
        channel.basicPublish(exchangeName,key4,null,"hello Key4".getBytes());

        channel.close();
        connection.close();
        System.out.println("发送消息成功");
    }
}

As shown in the above code, after execution, each of the four queues will receive a message. Among them, test_queue_name1 and test_queue_name2 each received a hello. The
matching requirements of Key1 direct are accurate. If you set the route to key1, you can only send it to key1 before receiving it. , sending key or key.1 will not be received
2. fanout

A fanout type switch will distribute the message to all queues bound to this switch. At this time, the RoutingKey parameter is invalid.
In other words, if a fanout type switch sends a message, no matter what the RoutingKey is, all queues will receive the message.

  1. Topic
    topic type switch, this type of switch is similar to Direct and also requires routing key for matching and distribution. The difference is that you can fuzzy query
    the Topic and divide the routing key into multiple parts through "."
    "*": represents a part
    "#": Represents 0-multiple parts, the routing key is #, which means accepting all information

  2. The performance of headers is too poor and I don’t want to study it.

Supongo que te gusta

Origin blog.csdn.net/qq_67548292/article/details/131904317
Recomendado
Clasificación