1. Overview of message queue
Objective: to be able to say what a message queue is; Why use message queuing; What are the common products
Summary:
Message queue is a communication method between applications; Asynchronous processing without immediate return and time-consuming operations, so as to improve the throughput of the system; Decoupling between programs can be realized.
- Implementation mode: AMQP, JMS
- Common products: activeMQ, zeroMQ, RabbitMQ, RocketMQ, kafka
2. Install and configure RabbitMQ
analysis:
- Install erlang;
- Install rabbitMQ;
- Install the graphical management interface plug-in of RabbitMQ;
- Create management users;
- Create Virtual Hosts
Summary:
When installing the above components, you need to run as an administrator.
3. Set up RabbitMQ introduction project
Objective: to build RabbitMQ entry project and configure corresponding maven dependencies
analysis:
Create Heima RabbitMQ's project; Used to test the messaging of RabbitMQ. Add a dependency to operate RabbitMQ.
<dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>5.6.0</version> </dependency>
Summary:
Create maven project with IDEA; jdk1.8 is used. The above dependencies are added to the pom.xml file in the project.
4. Introduction project - producer
Objective: write message producer code and send messages to the queue
analysis:
Entry project: the producer sends messages to the simple_queue of rabbit MQ; Consumers can get messages from the queue. You can use RabbitMQ's simple pattern.
Steps for the producer to send messages:
- Create a connection factory (set the connection parameters of RabbitMQ);
- Create a connection;
- Create channels;
- Declaration queue;
- Sending messages;
- close resource
Summary:
package com.itheima.rabbitmq.simple; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; /** * Simple mode: send message */ public class Producer { static final String QUEUE_NAME = "simple_queue"; public static void main(String[] args) throws Exception { //1. Create a connection factory (set the connection parameters of RabbitMQ); ConnectionFactory connectionFactory = new ConnectionFactory(); //host; Default localhost connectionFactory.setHost("localhost"); //Connection port; Default 5672 connectionFactory.setPort(5672); //Virtual host; Acquiescence/ connectionFactory.setVirtualHost("/itcast"); //user name; Default guest connectionFactory.setUsername("heima"); //password; Default guest connectionFactory.setPassword("heima"); //2. Create a connection; Connection connection = connectionFactory.newConnection(); //3. Create channels; Channel channel = connection.createChannel(); //4. Declaration queue; /** * Parameter 1: queue name * Parameter 2: whether to define a persistence queue (messages will be persisted and saved on the server) * Parameter 3: exclusive connection * Parameter 4: automatically delete queue when not in use * Parameter 5: other parameters */ channel.queueDeclare(QUEUE_NAME, true, false, false, null); //5. Send message; String message = "Hello! Rabbit paper."; /** * Parameter 1: switch name; If not, specify an empty string (indicating that the default switch is used) * Parameter 2: routing key. Queue name can be used in simple mode * Parameter 3: other properties of message * Parameter 4: message content */ channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); System.out.println("Sent message:" + message); //6. Close resources channel.close(); connection.close(); } }
When setting up the connection factory; If no connection parameter is specified, there will be a default value; You can set the virtual host.
5. Introduction project - consumers
Objective: write message consumer code, receive messages from the queue and consume them
analysis:
Receive messages from the RabbitMQ queue (consistent with the queue when the producer sends messages; simple_queue);
Steps to achieve customer satisfaction:
- Create a connection factory;
- Create a connection; (extract a tool class for obtaining connections)
- Create channels;
- Declaration queue;
- Create a consumer (receive messages and process messages);
- listen queue
Summary:
package com.itheima.rabbitmq.simple; import com.itheima.rabbitmq.util.ConnectionUtil; import com.rabbitmq.client.*; import java.io.IOException; /** * Simple mode; Consumer receives message */ public class Consumer { public static void main(String[] args) throws Exception { //1. Create a connection factory; //2. Create a connection; (extract a tool class for obtaining connections) Connection connection = ConnectionUtil.getConnection(); //3. Create channels; Channel channel = connection.createChannel(); //4. Declaration queue; /** * Parameter 1: queue name * Parameter 2: whether to define a persistence queue (messages will be persisted and saved on the server) * Parameter 3: exclusive connection * Parameter 4: automatically delete queue when not in use * Parameter 5: other parameters */ channel.queueDeclare(Producer.QUEUE_NAME, true, false, false, null); //5. Create a consumer (receive messages and process messages); DefaultConsumer defaultConsumer = new DefaultConsumer(channel){ @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { //Routing key System.out.println("route key Is:" + envelope.getRoutingKey()); //Switch System.out.println("The switch is:" + envelope.getExchange()); //Message id System.out.println("news id Is:" + envelope.getDeliveryTag()); //Received message System.out.println("The received message is:" + new String(body, "utf-8")); } }; //6. Listening queue /** * Parameter 1: queue name * Parameter 2: Auto confirm; Set to true to automatically reply to MQ when the message is received, and MQ will delete the message from the queue; * If set to false, manual confirmation is required * Parameter 3: Consumer */ channel.basicConsume(Producer.QUEUE_NAME, true, defaultConsumer); } }
You need to keep listening for queue messages, so don't close the resource
6. Entry engineering test
Objective: start the consumer and producer, query the queue in RabbitMQ, and view the received messages in the consumer's IDEA console
analysis:
Producer: send message to rabbit MQ queue (simple_queue)
Consumer: receiving RabbitMQ queue messages
Summary:
Simple mode: a producer sends a message to a queue, and a consumer receives a message from the queue.
In RabbitMQ, consumers can only receive messages from queues.
If the consumer receiving the message has two or more in the same queue; How are messages allocated?
7. Work queues
Objective: write producer and consumer code and test to understand the characteristics of Work queues mode
analysis:
Work queue mode: there can be multiple consumers in the same queue, and consumers compete for message reception.
Producer: send 30 messages
Consumer: create two consumers to listen to the same queue and check whether there are duplicates in the received messages of the two consumers.
Summary:
Work queue mode: a message can only be received by one consumer, and other consumers cannot receive the same message.
Application scenario: when processing tasks on the consumer side is time-consuming; Add consumers to the same queue to improve task processing capacity.
8. Description of subscription mode type
Objective: describe the role of Exchange switches in subscription mode and the three types of switches
Summary:
The subscription mode is compared with the previous two modes: an Exchange switch with an additional role receives messages sent by producers and decides how to deliver messages to its bound queue; The delivery of messages depends on the type of switch.
Switch type: broadcast, direct, topic
The switch only forwards messages and does not store data.
9. Publish/Subscribe publish and subscribe mode
Objective: write producer and consumer code, test and understand the characteristics of Publish/Subscribe publishing and subscription mode
analysis:
Publish and subscribe mode features: a message can be received by multiple consumers; In fact, the subscription mode is used. The switch type is fanout broadcast
- Producer (send 10 messages)
- Create a connection;
- Create channels;
- Declaration switch (fanout);
- Declaration queue;
- The queue is bound to the switch;
- Sending messages;
- close resource
- Consumer (at least two consumers)
- Create a connection;
- Create channels;
- Declaration switch;
- Declaration queue;
- The queue is bound to the switch;
- Creating consumers;
- Listening queue;
Summary:
Publish and subscribe mode: a message can be received by multiple consumers; For a consumer's queue, the queue can only be monitored by one consumer. The switch type in subscription mode is broadcast.
10. Routing mode
Objective: write producer and consumer code and test to understand the characteristics of Routing mode
analysis:
Producer: send two messages (the routing key s are insert and update respectively)
Consumer: create two consumers. The listening queues are bound with routing key s: insert and update
- In the message, if the key is insert, it will be received and processed by the consumer listening to the queue with the binding route key as insert;
- The message with the key of update will be received by the queue with the binding route key of update and monitored by the consumer;
Summary:
The Routing mode requires that the Routing key be specified when the queue is bound to the switch; The Routing key needs to be carried when the consumption is sent; Only when the Routing key of the message is completely consistent with that of the queue can the queue receive the message.
11. Topics wildcard mode
Objective: write producer and consumer code and test to understand the characteristics of Topics wildcard pattern
analysis:
- Producer: send three routing key messages including item.insert, item.update and item.delete
- Consumer 1: the route key s of the listening queue bound to the switch are: item.update, item.delete
- Consumer 2: the route key of the listening queue bound to the switch is: item*
Summary:
Topics wildcard mode: messages can be delivered to the queue of the corresponding routing key according to the routing key; The queue can have multiple routing keys bound to the switch; In the wildcard mode, the path key can use * and #; After using the wildcard mode, the configuration of routing key is more flexible.
12. RabbitMQ mode summary
Objective: To compare and summarize the characteristics of five modes of RabbitMQ
Summary:
- No direct Exchange switch (default switch)
- Simple simple mode: a producer produces a message to a queue and is received by a consumer
- work queue mode: producers send messages to a queue, and then multiple consumers can listen to the queue; A message can only be received by one consumer, and there is a competitive relationship between consumers
- Use Exchange switch; Subscription mode (switch: Broadcast fanout, directional direct, wildcard topic)
- Publish and subscribe mode: a fanout broadcast switch can send a message to all queues bound to the switch
- Routing mode: if a direct directional switch is used, the consumer will carry a routing key. The switch compares the message routing key with the queue routing key. If it is consistent, the queue can receive messages
- Wildcard mode: for switches using topic wildcard type, the consumer will carry the routing key (*, #). The switch compares the routing key of the message with the routing key of the queue. If it matches, the queue can receive the message
13. Create two projects for SpringBoot integration RabbitMQ
Objective: to create a springboot rabbitmq producer project for producing messages; Create a springboot rabbitmq consumer project to receive messages
analysis:
Spring Boot provides integration of AMQP; You can use RabbitTemplate to send messages; You can receive messages using the @ RabbitListener annotation.
Producer project springboot rabbitmq producer: send message
- Create project;
- Add dependencies (spring boot stat AMQP, spring boot starter test);
- Create boot class;
- Add configuration file application.yml
Consumer engineering springboot rabbitmq consumer: receive messages
- Create project;
- Add dependency (spring boot stat AMQP);
- Create boot class;
- Add configuration file application.yml
Summary:
You can use the plug-in to automatically produce the boot class Application.java and the configuration file application.yml of the Spring Boot project
14. Configuration Engineering
Objective: configure RabbitMQ of springboot RabbitMQ producer project, a switch, queue and bind
analysis:
Use wildcard mode: when binding a queue to a switch (topic), you need to specify a routing key (item. #)
- Configure the connection parameters of RabbitMQ: host, connection port, virtual host, user name and password;
- Declare the switch and queue, bind the queue to the switch, and specify the routing key (item. #)
Summary:
- Configure the application.yml file
spring: rabbitmq: host: localhost port: 5672 virtual-host: /itcast username: heima password: heima
- Configure switches, queues, and bindings, and create a configuration class
@Configuration public class RabbitMQConfig { //Switch name public static final String ITEM_TOPIC_EXCHANGE = "item_topic_exchange"; //Queue name public static final String ITEM_QUEUE = "item_queue"; //Claim switch @Bean("itemTopicExchange") public Exchange topicExchange(){ return ExchangeBuilder.topicExchange(ITEM_TOPIC_EXCHANGE).durable(true).build(); } //Declaration queue @Bean("itemQueue") public Queue itemQueue(){ return QueueBuilder.durable(ITEM_QUEUE).build(); } //Bind queue to switch @Bean public Binding itemQueueExchange(@Qualifier("itemQueue") Queue queue, @Qualifier("itemTopicExchange")Exchange exchange){ return BindingBuilder.bind(queue).to(exchange).with("item.#").noargs(); } }
15. Configure consumer Engineering
Objective: configure the RabbitMQ of the springboot RabbitMQ consumer project and write a message listener to receive messages
analysis:
- Configure the application.yml file and set the connection parameters of RabbitMQ;
- Write a message listener to receive an item_queue message; You can use the annotation @ RabbitListener to receive queued messages
Summary:
- Configure the application.yml file; Consistent with producer Engineering
- Writing listener classes
@Component public class MyListener { /** * Receive queue messages * @param message Received message */ @RabbitListener(queues = "item_queue") public void myListener1(String message){ System.out.println("Consumer received message:" + message); } }
The name of the queue receiving the message shall be consistent with the queue name when the producer sends the message
16. Test message sending and receiving
Objective: the producer writes the test class RabbitMQTest to send messages to the switch and specific routes (item.insert, item.update, item.delete)
analysis:
Producer: write a test class RabbitMQTest, and send three messages using RabbitTemplate. The routing key s of these three messages are item.insert, item.update and item.delete respectively
Consumer: check on the IDEA console to see if a message matching the routing key can be received
Summary:
Write test classes as follows:
package com.itheima.rabbitmq; import com.itheima.rabbitmq.config.RabbitMQConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class RabbitMQTest { @Autowired private RabbitTemplate rabbitTemplate; @Test public void test(){ rabbitTemplate.convertAndSend(RabbitMQConfig.ITEM_TOPIC_EXCHANGE, "item.insert", "Commodity addition,route Key by item.insert"); rabbitTemplate.convertAndSend(RabbitMQConfig.ITEM_TOPIC_EXCHANGE, "item.update", "Commodity addition,route Key by item.update"); rabbitTemplate.convertAndSend(RabbitMQConfig.ITEM_TOPIC_EXCHANGE, "item.delete", "Commodity addition,route Key by item.delete"); rabbitTemplate.convertAndSend(RabbitMQConfig.ITEM_TOPIC_EXCHANGE, "a.item.delete", "Commodity addition,route Key by a.item.delete"); } }
Start the test class to declare the switch, queue and binding; Then start the consumer engineering to receive the message.