This is the 21st day of my participation in Gwen Challenge
Accumulate over a long period, constant dripping wears away a stone 😄
preface
RabbitMQ has been introduced in two previous articles. This article will show you how to use RabbitMQ in SpringBoot.
Environment set up
Import dependence
pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Copy the code
Configuration Configuration file
Configure basic RabbitMQ information in the configuration file, including IP, port, USERNAME, password, and virtual-host. This should be familiar to you if you read the first article.
spring:
application:
name: rabbitmq-boot
rabbitmq:
host: 47.105198.54.
port: 5672
virtual-host: /test-1
username: * * *
password: * * * *
Copy the code
SpringBoot uses RabbitTemplate to simplify RabbitMQ operations and can be injected directly into a project.
use
Next, we will show you how to use the RabbitMQ message model in SpringBoot.
Hello world model
There is a producer for every consumer.
1. Develop producers
@Autowired
RabbitTemplate rabbitTemplate;
@Test
void testHello(a){
/** * Parameter 1: queue name * Parameter 2: message content */
rabbitTemplate.convertAndSend("hello-boot"."hello boot");
}
Copy the code
Note: Since we have not written the consumer yet, running the above producers alone does not create a queue; the queue is created by the consumer
2. Develop customers
@Component
public class HelloCustomer {
// Create a Hello-boot queue with annotations
@RabbitListener(queuesToDeclare = { @Queue(value = "hello-boot",durable = "false", autoDelete = "false") })
public void consumptionStr(String message){
System.out.println("Consumer News:+ message); }}Copy the code
Methods annotated with the @RabbitListener annotation will be used as methods for consuming messages, i.e. consumers; We can specify the queue or Binding to listen on via the annotation parameter.
The @queue annotation can set Queue properties, such as:
- Value: indicates the queue name
- Durable: Whether to be persistent
- “AutoDelete” : indicates whether to automatically delete the vm
RabbitMQ properties: RabbitMQ properties
Then run the testHello method of the producer.
Result: Consumer message: Hello bootCopy the code
The work model
One producer for many consumers.
1. Develop producers
@Test
void testWork(a){
/** * Parameter 1: queue name * Parameter 2: message content */
for (int i = 0; i < 10; i++) {
rabbitTemplate.convertAndSend("work-boot"."work boot"); }}Copy the code
2. Develop customers
@Component
public class WorkCustomer {
// Create a work-boot queue with annotations
@RabbitListener(queuesToDeclare = @Queue("work-boot"))
public void work1(String message){
System.out.println("Consumer News -1:" + message);
}
@RabbitListener(queuesToDeclare = @Queue("work-boot"))
public void work2(String message){
System.out.println("Consumer News -2:"+ message); }} Result: consume message -1: Work boot consumption message -1: Work boot consumption message -2: Work boot consumption message -2: Work boot consumption message -2: Work boot consumption message -2: Work boot consumption message -2: Work boot consumption message -1: Work boot consumption message -1: Work boot consumption message -1: the work bootCopy the code
According to the results, we can find that two consumers each consumed 5 messages. Spring AMQP is fair scheduling. Additional configuration is required if you want to achieve versatility
The fanout model
A new member has been added to this model, called a switch. Messages are distributed by MQ to the switch, which then sends them to queues.
1. Develop producers
@Test
void testfanout(a){
/** * Parameter 1: switch name * Parameter 2: route name (in FANout mode, this parameter has no effect) * Parameter 3: message content ** /
rabbitTemplate.convertAndSend("fanout-boot-exchange".""."fanout boot");
}
Copy the code
2. Develop customers
@RabbitListener(bindings = { @QueueBinding( value = @Queue, Exchange = @exchange (value = "fanout-boot-exchange", type = "fanout")})
public void fanoutStr(String message){
System.out.println("Consumer News -1:" + message);
}
@RabbitListener(bindings = { @QueueBinding( value = @Queue, Exchange = @exchange (value = "fanout-boot-exchange", type = "fanout")})
public void fanoutStr2(String message){
System.out.println("Consumer News -2:"+ message); } Result: consume message -2: Fanout boot consumption message -1: the fanout bootCopy the code
The @queueBinding annotation is used to bind queues and switches.
The @exchange annotation is used to declare the switch.
According to the printed results, it can be found that all consumers in the queue can get the message. Implement a message to be consumed by multiple consumers.
The Route model
In Fanout mode, a message is consumed by all subscribed queues. However, in some scenarios, we want different messages to be consumed by different queues. This is where Exchange of type Direct is used.
1. Develop producers
@Test
void testDirect(a){
/** * Parameter 1: switch name * Parameter 2: route name * Parameter 3: message content ** /
rabbitTemplate.convertAndSend("direct-boot-exchange"."error"."direct boot error");
}
Copy the code
2. Develop customers
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class directCustomer {
@RabbitListener(bindings = { @QueueBinding(value = @Queue, Exchange = @exchange (value = "direct-boot-exchange", // bind the switch name and type, The default type is direct type = "direct"), key = {"info"}) // Route key})
public void directStr(String message){
System.out.println("Consumer News -1:" + message);
}
@RabbitListener(bindings = { @QueueBinding(value = @Queue, exchange = @Exchange(value = "direct-boot-exchange", Type = "direct"), key = {" info ", "error"}) / / routing key})
public void directStr2(String message){
System.out.println("Consumer News -2:"+ message); }}Copy the code
The route key is error
Consumption News -2: direct boot errorCopy the code
The key for sending routes is INFO
Consumption News -1: Direct boot info Consumption message -2: direct boot infoCopy the code
Topic model
The Topic typeExchange
与 Direct
Compared with, can be based onRoutingKey
Route messages to different queues. onlyTopic
The type ofExchange
You can make the queue bindRouting key
When usingThe wildcard! This modelRoutingkey
It is usually made up of one or more words, with “between” words. Split, for example, user.insertThere are two wildcards
* : Match 1 word
# : Matches one or more words
Such as:
- Audit.# Match audit.irs.corporate or audit.irs
- Audit.* matches only audit.irs
1. Develop producers
@Test
void testTopic(a){
/** * Parameter 1: switch name * Parameter 2: route name * Parameter 3: message content ** /
rabbitTemplate.convertAndSend("topic-boot-exchange"."user.role.query"."topic boot user.role.query");
}
Copy the code
2. Develop customers
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class TopicCustomer {
@RabbitListener(bindings = { @QueueBinding(value = @Queue, exchange = @Exchange(value = "topic-boot-exchange", type = "topic"), key ={"user.*"}) })
public void topicStr(String message){
System.out.println("Consumer News -1:" + message);
}
@RabbitListener(bindings = { @QueueBinding(value = @Queue, exchange = @Exchange(value = "topic-boot-exchange", type = "topic"), key ={"user.#"}) })
public void topicStr2(String message){
System.out.println("Consumer News -2:"+ message); }}Copy the code
The key of the sent route is user.role-query
Consumption News -2: topic boot user. Role. The queryCopy the code
The key for sending the route is user.query
Consumption News -2: topic boot user.query Consume messages -1: topic boot user queryCopy the code
- If you have any questions or errors in this article, please feel free to comment. If you find this article helpful, please like it and follow it.