The basic concept

Publisher (Publisher)

The publisher (or producer) is responsible for producing the message and delivering it to the specified exchange.

A Consumer

Consumer, consumer producer generated information.

Exchange

RabbitMQ receives messages from Producer and forwards them to the corresponding Queue. There are four types of Exchanges for RabbitMQ. Each type of Exchange forwards messages differently.

  • Direct Exchange: The Direct Exchange compares the routing key and Queue of the message with the Binding key of the Exchange, and forwards the message to the Queue that is a complete match (equivalent value). The binding key of the Queue = routing key. As shown in the following figure, when the RountingKey of the message is orange, the message will be routed to Q1 queue. When the RountingKey of a message is black or green, the message is routed to Q2 queue.

When a switch is bound to multiple queues, their Bindingkeys can be the same, as shown below. When the RountingKey of the message is black, the message is routed to both Q1 and Q2 queues.

  • Topic Exchange: The Topic Exchange run matches routing keys with binding keys.

    Routing keys and binding keys are used by multiple words. To connect

    • BindingKey supports two special symbols:#*. Among them*To match a word,#Matches zero or more words.

    The following is an example from the official documentation. The binding of the switch to the queue is shown here, and the routing is as follows:

    • A message with a route key of lazy.orange.elephant is sent to all queues;

    • A message with a routing key of quick.orange.fox is sent only to queue Q1;

    • A message with a route key of lazy.brown.fox is only sent to the Q2 queue;

    • A message with a route key of lazy.pink.rabbit will only be sent to Q2 queue;

    • A message with a routing key of Quick.brown. fox does not match any binding;

    • Messages with routing keys orange or quick.orange.male. Rabbit also do not match any bindings.

  • Fanout Exchange: Fanout Exchange is a message broadcast mode that does not match routing keys and delivers messages directly to all queues bound to the Fanout Exchange. It acts like a radio station that sends messages to all users listening to the broadcast.

  • Headers Exchange(rarely used)

###Queue

A queue for storing messages. It is bound to Exchange via a binding key.

Routing Key

An attribute of the message, which can be regarded as the type of the message (customized by the business). For example, when sending logs of different levels of the program as messages, the error-level messages can use log.error as the routing key.

Binding Key

A property of a Queue bound to Exchang, which can be seen as the type of business message the Queue is interested in. Exchange will decide whether to forward the message to a Queue based on the routing key and binding key of the message.

Virtual Host

RabbitMQ uses virtual hosts for logical grouping and resource isolation. Each virtual host can be considered a separate namespace with separate queues, switches, and bindings. Users can set up different virtual hosts according to different service scenarios. Virtual hosts are completely independent from each other. You cannot bind the switch on Vhost1 to the queue on Vhost2, which greatly ensures the isolation and data security between services. The default virtual host name is /.

Spring Boot integrates RabbitMQ

1. Introduce dependencies

Spring Boot is very easy to integrate with RabbitMQ, but with very little configuration for simple use, Spring Boot provides a variety of spring-boot-starter-AMQP project support for messages.

<! --rabbbitMQ dependencies --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>Copy the code

2. Set the RabbitMQ server connection address, port number, account, and password

# RabbitMQ server connection port (default: 5672)
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
Copy the code

Note: Guest is the default user name and password for logging in to rabbitMQ and can only log in to the local rabbitMQ server. If MQ is not deployed on the local computer, you need to add users and set user rights.

3. Add the RabbitMQ configuration class and configure Queue, Exchange, and Binding

@Configuration
public class RabbitMQConfig {
    /** * Queue for receiving WARN level log messages *@return* /
    @Bean
    public Queue warnQueue(a) {
        // Queue name, which is equivalent to new Queue(name, true, false, false)
        Durable = true, exclusive = false, autoDelete = false
        return new Queue("warn.queue");
    }

    /** * The queue used to receive error level log messages *@return* /
    @Bean
    public Queue errorQueue(a) {
        return new Queue("error.queue");
    }

    /** * The queue used to receive log messages of all levels *@return* /
    @Bean
    public Queue allQueue(a) {
        return new Queue("all.queue");
    }

    /** * Create a switch *@return* /
    @Bean
    public TopicExchange topicExchange(a){
        // New TopicExchange(name, true, false)
        Durable = true, autoDelete = false
        return new TopicExchange("log.topic.exchange");
    }

    @Bean
    public Binding binding(a){
        // Bind queues to switches. Bind three elements: Queue, Exchange, and Binding Key
        return BindingBuilder.bind(warnQueue()).to(topicExchange()).with("log.warn");
    }

    @Bean
    public Binding binding1(a){
        return BindingBuilder.bind(errorQueue()).to(topicExchange()).with("log.error");
    }
    
	/** * uses log.* to match log messages * for log.warn and log.error@return* /
    @Bean
    public Binding binding2(a){
        return BindingBuilder.bind(allQueue()).to(topicExchange()).with("log.*"); }}Copy the code

Note: The Queue, Exchange, and Binding configured here will be created in the RabbitMQ server when messages are sent.

4. Send messages

Send messages using AmqpTemplate, directly injected.

@RunWith(SpringRunner.class)
@SpringBootTest
public class SenderTest {
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Test
    public void sendWarnLog(a){
        // The parameters are the target Exchange, the routingKey of the message, and the body of the message
        amqpTemplate.convertAndSend("log.topic.exchange"."log.warn"."this is a warn log"); }}Copy the code

The rabbitMQ console can check the successful sending of the message by running the test method:

You can see that the three queues we configured and the switch have been created successfully, and the warning level log messages we sent have been forwarded to all.queue and WARN. Queue.

5. Consumer news

@Service
@Slf4j
public class Consumer {
    /** * specifies the queue to consume */
    @RabbitListener(queues = "warn.queue")
    public void consume(String message){
        log.info("Consume message: {}", message); }}Copy the code

Note: The message sent in the example is a string. To send an object, the object needs to implement the Serializable interface.