Haven’t used RabbitMQ for a long time, easy to remember, want to sort out.

1. Install the rabbitmq

The environment I choose is Docker. If you are not familiar with Docker, please check it out. It’s great.

1. Install, I choose to install management version,management has its own web operation page version.

docker pull rabbitmq:3.715.-management
Copy the code

2. Start:

docker run -d --name rabbitmq -p 5672:5672 -p 15672:15672 
-v `$pwd`/data:/var/lib/rabbitmq --hostname myrabbit 
-e RABBITMQ_DEFAULT_USER=guest 
-e RABBITMQ_DEFAULT_PASS=guest 
rabbitmq:3.714.-management 
Copy the code

3. Check whether the startup is successful.

docker ps // The service description is successfully started
localhost:15672 // Browser access
Copy the code

The rabbitMQ installation is successful.

2. Basic introduction to message services

A brief introduction to the messaging service to deepen the impression.

Why use a messaging service? In most applications, the asynchronous communication ability and decoupling ability of the system can be improved through message middleware.

Application scenarios: asynchronous processing, decoupling, flow peak cutting

Two important concepts in message service: 1. Message Broker 2. When a message sender sends a message, the message broker takes over. The message broker ensures that our messages reach the specified destination.

Message queues have two main forms of destination:

1. Queue: point-to-point message communication 2. Topic: publish/subscribe message communication

Point-to-point: One-to-one, after a message publisher publishes a message, the message broker puts the message into a specified queue, and the message receiver obtains the message content from the queue. After the message receiver reads the message, the message is removed from the queue. Both sender and receiver are unique (meaning that the same message can only be received by one message receiver)

Publish-and-subscribe: A message publisher sends a message to a topic, and multiple message receivers listen to the topic and receive messages arriving at the topic.

Message services are divided into JMS and AMQP:

JMS(Java Message Service): Specification based on JVM Message broker. For example, ActiveMQ is the implementation of JMS. This parameter is valid only in the Java language.

Rabbitmq is an implementation of the Advanced Message Queuing Protocol (AMQP), an Advanced Message Queuing Protocol (AMQP) that is compatible with JMS.

3.Rabbitmq

The RabbitMQ introduction:

RabbitMQ is an open source implementation of the Advanved Message Queue Protocol (AMQP) developed by Erlang

Key Concepts:

Message: a Message consisting of a header and a body. The body of the message is opaque, and the header consists of a set of optional attributes, including routing-key, priority (priority over other messages),delivery-mode(indicating whether the message needs to be persisted), and so on.

Publisher: Message producer and client application that publishes messages to the exchange.

Exchange: An Exchange that receives messages sent by message producers and routes them to queues in the server. Exchange has four types: Direct (default), Fanout, Topic, and headers. Different types of exchanges have different policies for forwarding messages.

Queue: A message Queue, used to hold messages until they are sent to consumers. It is a container for messages and a grave for messages. Messages remain in the message Queue until the consumer connects to the Queue to retrieve them.

A Binding is a routing rule that connects a switch to a message queue based on a routing key, so a switch can be thought of as a routing table made up of bindings. The Exchange and Queue bindings can be many-to-many.

Connection: indicates the network Connection. Such as a TCP connection

Channel: Channel, an independent two-way data Channel in a multiplexing connection. A channel is a virtual connection established within a real TCP connection. AMQP commands are sent through the channel. No matter publishing messages, subscribing to queues or receiving messages, these actions are completed through the channel. Because it is very expensive for an operating system to establish and destroy TCP, the concept of a channel was introduced to reuse a TCP connection.

Consumer: Message Consumer, representing a client application that retrieves messages from a message queue.

Virtual Host: a Virtual Host representing a batch of switches, message queues, and related objects. A virtual host is a separate server domain that shares the same authentication and encryption environment. Each virtual host is essentially a mini Rabbitmq server with its own queues, switches, bindings and permissions. Virtual hosts are the basis of the AMQP concept and must be specified at connection time. The default vhost for RabbitMq is /

Broker: Entity that represents a message queue server

4. The type of rabbitMQ is Exchange

Exchange distributes messages according to different distribution policies. Currently, there are four types: Fanout 3. Topic 4. Headers (Headers match the header of an AMQP message rather than the routing key, which is the same as direct and has poor performance.)

Direct Exchange: If the routing key in the message matches the Binding key in Binding, the Exchange sends the message to the corresponding message queue. It is perfectly matched, unicast mode.

Fanout Exchange: Every message sent to a FanoutExchange-type Exchange is distributed to all message queues bound to the Exchange. The Fanout Exchange does not handle routing keys and simply binds the queue to the Exchange. Every message sent to the exchange is sent to all queues bound to it. Broadcast mode, forwarding messages is the fastest.

Topic Exchange: The Topic Exchange allocates the routing key attribute of the message through pattern matching, matching the routing key to a pattern in which the queue is bound. It splits the string of routing keys and bindings into words separated by dots. In short, matching patterns

4. Springboot integration with RabbitMQ

Integration can be divided into the following steps: 1. Introduction of Spring-boot-starter-AMQP Maven dependency 2. Yml 3. Bind the switch to the route 4. Message publishing and receiving

1. Introduce dependencies

<dependencies> <! GroupId > <artifactId> Spring-boot-starter -web</artifactId> </dependency> <! --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> <! > <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> </dependencies>Copy the code

2. Configuration yml

Spring: application: name: rabbitmq-provider rabbitMQ: # username: admin # password: admin #5672# IP host: localhost #vhost path virtual-host: / listener: simple: acknowledge-mode: manual server: port:8083
Copy the code

3. Configure routes, switches, and bind them

@Configuration
public class DirectRabbitmqConfig {

    /** Create Queue01 */
    @Bean
    public Queue getQueue01(a){
        // Parameter 1 queue name
        // Whether parameter 2 is persistent
        // Whether parameter 3 can only be used by the currently created connection and destroy the queue after the connection is closed
        // Parameter 4 is automatically destroyed when the queue is empty
        // Parameter 5 5 Other configuration information
        return new Queue("Queue01".true);
    }
    
    /** Create a Direct switch */
    @Bean
    public DirectExchange getDirectExchange01(a){
        return new DirectExchange("DirectExchange01".true.true);
    }
    
    /** Bind routes to switches */
    @Bean
    public Binding bingQueueWithDirectExchange01(a){
        // Bind the route to the switch and set the matching key
        return BindingBuilder.bind(getQueue01()).to(getDirectExchange01()).with("DirectRouting01"); }}Copy the code

4. Message publishing and receiving At the last stage, let’s write interfaces for message publishing and receiving.

@RestController
public class RabbitController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /** Use rabbitTemplate send to send messages */
    @GetMapping("/sendMessage/{number}")
    public ResponseEntity<String> sendMessage(@PathVariable("number") String number){
        // Specify the message type
        MessageProperties build = MessagePropertiesBuilder.newInstance().setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN).build();
        / / send
        rabbitTemplate.send("TestExchange1"."TestQueue1".new Message(number.getBytes(StandardCharsets.UTF_8),build));
        return ResponseEntity.ok("Sent successfully :"+number);
    }

    /** Use the convertAndSend method of rabbitTemplate to send messages */
    @GetMapping("/convertAndSendMessage/{number}")
    public ResponseEntity<String> convertAndSendMessage(@PathVariable("number") String number){
        rabbitTemplate.convertAndSend("TestExchange1"."TestQueue1",number);
        return ResponseEntity.ok("Sent successfully :"+number); }}Copy the code

Start the service and access the service path The message is received when it is seen in the message queue. Message push success. now we write code to receive the message to create a listener class that listens on the specified queue

@Component
@RabbitListener(queues = {"Queue01"})
public class MyRabbitListener {
    @RabbitHandler
    public void accept(String message){
        System.out.println("Received message :"+message); }}Copy the code

Restart the service againRabbitmq is now integrated with Springboot, and other types of Exchange APIS will not be discussed.