The premise

Asked me to our project manager for the last week of the original upgrade project, using the message queue processing orders, is no longer in the processing of orders all logic serial, heard the news, I’ll nervous, serial processing has been before, now how to use mq, and I also used the mq, search data, learn quickly Hence this article.

rabbitmq

Of all the message queuing middleware, I chose RabbitMQ for learning, both because it is easy to install and because there is an official Spring starter for my first use.

Docker pull RabbitMQ: Management

Docker run -d -p 5672:5672 -p 15672:15672 –name rabbitmq rabbitMQ :management, where port 15672 is the exposed port of the Web. Visit http://localhost:15672, username&password for guest.

rabbitmq starer

Integrate RabbitMQ into Spring Boot and add dependencies

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

In the application. The yml configuration

Spring: rabbitmq: host: 127.0.0.1 Port: 5672 username: guest Password: guest virtualHost: /Copy the code

RabbitmqConfig

@configuration public class RabbitmqConfig {public static final String QUEUE_HELLO = "QUEUE_HELLO "; public static final String EXCHANGE_HELLO = "exchange_hello"; @bean (EXCHANGE_HELLO) Public Exchange EXCHANGE_TOPICS() {// Durable (true) Switches return after restarts ExchangeBuilder.directExchange(EXCHANGE_HELLO).build(); } @bean (QUEUE_HELLO) public Queue Queue() {return new Queue(QUEUE_HELLO); } @bean public Binding BINDING_QUEUE(Queue Queue, DirectExchange exchange) { return BindingBuilder.bind(queue).to(exchange).withQueueName(); }}Copy the code

ReceiveHandler listener

@Component public class ReceiveHandler {// Queue = {rabbitmqconfig. QUEUE_HELLO}) public void @component Public class ReceiveHandler {// Queue = {rabbitmqconfig. QUEUE_HELLO}) public void receiveMsg(String msg, Message message, Channel channel){ System.out.println(msg); }}Copy the code

To the Web end to send messages. Queues to enter the queues we have just created.

Find the Publish Message, enter Content-type =text/plain in the properties field, payload fill in the content to be sent to the queue.

Cutting back to idea, we can see what was just sent to the queue on the Web side.

Send messages through Java code.

Start the test case and you can see the message sent to the queue.

The rabbitmq switches

Basic logic in RabbitMQ.

There are four relationships between exchanges and queues.

  • Fanout Fanout-exchange mode, which pushes messages to all queues bound to it;
  • Direct direct-exchange mode, which pushes messages to the queue bound to it, with the RoutingKey matching exactly. (Default mode)
  • Topic topic-Exchange pattern, familiar with direct-exchange pattern, but RoutingKey does fuzzy matching.
  • Headers Messages are distributed based on headers.

This is the basic use of RabbitMQ in Spring Boot.