current position:Home>[spring boot 7] rabbitmq basic knowledge summary, mybatis operation principle

[spring boot 7] rabbitmq basic knowledge summary, mybatis operation principle

2022-01-26 21:34:05 m0_ fifty-four million eight hundred and sixty-one thousand fou

After installation rabbitMq after , Input http://ip:15672/ , You can see a simple background management interface .

Two 、RabbitMQ Characteristics

=============

1、 It is designed as a general message broker service , Support peer-to-peer 、 request - reply 、 Release - Subscription, etc .

2、 Focus on message consistency 、 Reliability and stability .

3、 Yes Java、.net、node.js、PHP And other languages have very good support , And there are rich plug-ins to provide function expansion , Nothing can't be done, only unexpected .

4、 Support synchronous or asynchronous message communication , Support distributed deployment and multi node cluster deployment , Can provide 2 ten thousand / Second message distribution capability , Inferior in performance kafka.

3、 ... and 、RabbitMQ Related concepts of

===============

Usually we talk about queue services , There will be three concepts : The messenger 、 queue 、 The receiver ,RabbitMQ On top of this basic concept , There's an extra layer of abstraction , A switch is added between the sender and the queue exchange, In this way, the sender has no direct contact with the queue , Instead, program the messenger to send the message to the switch , The switch sends the message to the queue according to the scheduling strategy .

The yellow circle is our message push service , Push the message to the middle box , That is to say RabbitMQ The server , And then through the switch in the server 、 Various relationships such as queues list data processing , Finally, the blue circle on the right side of the consumer gets the corresponding monitoring message .

that , There are four important concepts , Namely : Virtual host 、 Switch 、 Queues and bindings .

  • Virtual host : A virtual host holds a set of switches 、 Queues and bindings . Why multiple virtual hosts are needed ? It's simple , RabbitMQ  among , Users can only control permissions at the granularity of the virtual host . therefore , If you need to ban A Group visit B Group switches 、 queue 、 binding , It has to be for A and B Create a virtual host 、 every last  RabbitMQ  Servers have a default virtual host “/”.

  • Switch :Exchange Used to forward messages , But it doesn't do storage , without queue bind To Exchange Words , It will throw away Producer Messages sent . Here is an important concept : Routing key . When the message arrives at the switch , The switch forwards to the corresponding queue , So which queue to forward to , According to the routing key .

  • binding : That is, the switch needs to be bound to the queue , This is shown in the picture above , It's a many-to-many relationship .

Switch (Exchange)


The main function of the switch is to receive messages and forward them to the bound queue , The switch does not store messages , In the activation of ack After the model , If the switch cannot find the queue, it will return an error . There are four types of switches :Direct 、Topic、Headers、Fanout

  • Direct :direct The type of behavior is “ Match first and then deliver ”, That is, when binding, set a routing_key, News routing_key When the match , Will be sent to the bound queue by the switch .

  • Topic: Forward messages according to rules ( Most flexible )

  • Headers: Set up header attribute Switch of parameter type ( Basically not )

  • Fanout: Forward messages to all binding queues

1、Direct Exchange yes RabbitMQ Default switch model , It's also the simplest model , according to key Full text matching to find queues .

first X - Q1 There is one binding key, The name is orange; X - Q2 There is 2 individual binding key, The name is black and green. When in the news Routing key and This binding key Corresponding time , Then we know which queue the message goes to .

Ps: Why? X To Q2 Want to have black,green,2 individual binding key Well , Not one ? - This is mainly because there may be Q3, and Q3 We only accept black Information about , and Q2 Not only accept black Information about , And accept green Information about .

2、Topic Exchange

Topic Exchange Forwarding messages is mainly based on wildcards . Under this switch , The binding of queues and switches defines a routing pattern , that , The wildcard must be matched between the routing mode and the routing key before the switch can forward messages .

In this switch mode :

(1) The routing key must be a string of characters , Separate... With a full stop , for instance agreements.us, perhaps agreements.eu.stockholm etc. .

(2) The routing mode must contain an asterisk (*), It is mainly used to match a word in the specified location of the routing key , for instance , A routing pattern is like this : agreements…b.*,  Then it can only match the routing key like this : The first word is agreements, The fourth word is b. A pound sign is equivalent to one or more words , For example, a matching pattern is  agreements.eu.berlin.#, that , With agreements.eu.berlin The routing keys at the beginning are all ok .

When the specific code is sent, it is still the same , The first parameter represents the switch , The second parameter represents routing key, The third parameter is the message . as follows :

rabbitTemplate.convertAndSend(“testTopicExchange”,“key1.a.c.key2”, " this is RabbitMQ!");

topic and direct similar , It's just a match ” Pattern ”, stay ” Point and point ” Of routing_key In form , You can use two wildcards :

* To express a word

# Means zero or more words

3、Header Exchange

headers Also match according to the rules , Compare with direct and topic To use regularly routing_key , headers It is a type of custom matching rule . When the queue is bound to a switch , A set of key value pair rules will be set , The message also includes a set of key value pairs ( headers attribute ), When these key value pairs have a pair , Or all of them , The message is sent to the corresponding queue .

4、 Fanout Exchange

Fanout Exchange   The mode of message broadcasting , No matter routing key or routing mode , The message will be sent to all queues bound to it , If the routing_key Will be ignored .

Four 、rabbitmq What are the important components ?

==================

1、ConnectionFactory( Connection manager )


Application and RabbitMQ The manager that establishes the connection between .

2、Channel( channel )


Channel used for message push .

3、RoutingKey( Routing key )


It's used to distribute data from producers to switches .

4、Exchange( exchanger )


To accept 、 Assign messages .

5、BindKey( Binding key )


Used to bind messages from the switch to the queue

6、Queue( queue )


Used to store producer's messages .

5、 ... and 、RabbitMQ The applicable scenarios of

===============

1、 Asynchronous processing


The scene that : After user registration , You need to send registration email and registration SMS .

There are two traditional approaches ,① Serial mode ;② In parallel ;

(1) Serial mode

After writing the registration information to the database , Send registration email , Resend registration SMS , After the above three actions are completed, it will be returned to the client .

The problem with this method is that sending registration email and sending registration SMS are not necessary , It's just a notice , This way the client waits for something that doesn't have to wait , Impact on user experience .

(2) Parallel mode

After writing the registration information to the database , While sending mail , Send a text message , After the above three operations are completed , Return to the client , The parallel method can shorten the processing time .

Suppose that the three business nodes use 50ms, Serial mode is 150ms, The parallel way is 100ms.

Although parallelism has reduced processing time , But I said before , Email and SMS are not necessary , There is no need for customers to wait for a response , It should be written to the database and returned directly .

(3)  Message queue RabbitMQ

After message queuing is introduced , The response time of the user is equal to the time of writing to the database + Time to write to message queue ( Negligible ), After message queuing is introduced , Significantly reduced response time .

2、 The application of decoupling


(1) scene

double 11 It's the shopping Carnival , After the user orders , Order system needs to inform inventory system , The traditional way is that the order system calls the inventory system interface .

(2) shortcoming

Due to the high coupling between order system and inventory system , When the inventory system breaks down , The order will fail .

(3) Import message queue RabbitMQ

Order system : After the user orders , Order system completes persistent processing , Write message to message queue , Return to user's order successfully placed .

inventory system : Subscribe to the message of the order , Get the order message , Perform library operations . Even if the inventory system breaks down , Message queuing can also ensure the reliable delivery of order messages , Will not result in the loss of messages .

3、 Traffic peak clipping


Flow peak clipping is widely used in seckill activities

scene : Seckill activity , It's usually because of too much traffic , Cause the app to hang up , To solve this problem , Generally, the message queue is added to the front end of the application .

(1) effect

① Can control the number of activities , Orders exceeding this threshold are discarded directly . This is the general principle of second kill .

② It can alleviate the crushing application of high flow in a short time ( The application gets the order according to its maximum processing capacity ).

(2) User's request , When the server receives it , Write message queue first , The length of joining message queue exceeds the maximum , Discard the user request or jump to the error page directly .

(3) Seckill service according to the request information in the message queue , Follow up .

6、 ... and 、springboot Integrate RabbitMQ

======================

Spring Boot Integrate RabbitMQ It's simple , If it's just a simple configuration, it's very few ,Spring Boot Provides spring-boot-starter-amqp The project supports all kinds of messages .

1、pom.xml


org.springframework.boot

spring-boot-starter-amqp

2、 To configure RabbitMQ Installation address of 、 Port and account information


spring.application.name=Spring-boot-rabbitmq

spring.rabbitmq.host=192.168.0.86

spring.rabbitmq.port=5672

spring.rabbitmq.username=admin

spring.rabbitmq.password=123456

3、 Queue configuration


@Configuration

public class RabbitConfig {

@Bean

public Queue Queue() {

return new Queue(“hello”);

}

}

4、 sender


rabbitTemplate yes Spring Boot The default implementation provided

@component

public class HelloSender {

@Autowired

private AmqpTemplate rabbitTemplate;

public void send() {

String context = "hello " + new Date();

System.out.println("Sender : " + context);

this.rabbitTemplate.convertAndSend(“hello”, context);

}

}

5、 The receiver


@Component

@RabbitListener(queues = “hello”)

public class HelloReceiver {

@RabbitHandler

public void process(String hello) {

System.out.println("Receiver : " + hello);

}

}

6、 test


@RunWith(SpringRunner.class)

@SpringBootTest

public class RabbitMqHelloTest {

@Autowired

private HelloSender helloSender;

@T

《 A big factory Java Analysis of interview questions + Back end development learning notes + The latest architecture explanation video + Practical project source code handout 》

【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 Full content open source sharing

est

public void hello() throws Exception {

helloSender.send();

}

}

Of the sender and the receiver queue name It has to be consistent , Otherwise, we can't accept

7、 ... and 、 Many to many use

=======

A sender ,N A receiver or N A sender and N What happens to a recipient ?

1、 One to many send


The code above has been slightly modified , The receiver registers two Receiver,Receiver1 and Receiver2, The sender adds parameter count , The receiving end prints the received parameters , Here is the test code , Send a hundred messages , To observe the execution effect of the two receivers

@Test

public void oneToMany() throws Exception {

for (int i=0;i<100;i++){

neoSender.send(i);

}

}

give the result as follows :

Receiver 1: Spring boot neo queue ****** 11

Receiver 2: Spring boot neo queue ****** 12

Receiver 2: Spring boot neo queue ****** 14

Receiver 1: Spring boot neo queue ****** 13

Receiver 2: Spring boot neo queue ****** 15

Receiver 1: Spring boot neo queue ****** 16

Receiver 1: Spring boot neo queue ****** 18

Receiver 2: Spring boot neo queue ****** 17

Receiver 2: Spring boot neo queue ****** 19

Receiver 1: Spring boot neo queue ****** 20

According to the returned results, the following conclusions are obtained

A sender ,N A receiver , After testing, the message will be sent to N Of the recipients

2、 Many to many sending


A copy of the sender , Add a marker , Send alternately in a hundred cycles

@Test

public void manyToMany() throws Exception {

for (int i=0;i<100;i++){

neoSender.send(i);

neoSender2.send(i);

}

}

give the result as follows :

Receiver 1: Spring boot neo queue ****** 20

Receiver 2: Spring boot neo queue ****** 20

Receiver 1: Spring boot neo queue ****** 21

Receiver 2: Spring boot neo queue ****** 21

Receiver 1: Spring boot neo queue ****** 22

Receiver 2: Spring boot neo queue ****** 22

Receiver 1: Spring boot neo queue ****** 23

Receiver 2: Spring boot neo queue ****** 23

Receiver 1: Spring boot neo queue ****** 24

Receiver 2: Spring boot neo queue ****** 24

Receiver 1: Spring boot neo queue ****** 25

Receiver 2: Spring boot neo queue ****** 25

Conclusion : It's the same as one-to-many , The receiver will still receive the message evenly .

8、 ... and 、 Advanced use

======

1、 Object support


springboot Perfect support for sending and receiving objects , No additional configuration required .

// sender

public void send(User user) {

System.out.println("Sender object: " + user.toString());

this.rabbitTemplate.convertAndSend(“object”, user);

}

copyright notice
author[m0_ fifty-four million eight hundred and sixty-one thousand fou],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201262134027838.html

Random recommended