Rabbit Mq docker installation and springboot

Posted by werushka on Fri, 17 May 2019 13:56:17 +0200

A Brief Introduction to RabbitMQ Core Nouns

Publisher: Message Producer

Exchange: Exchange, which receives messages from producers and routes them to queues in servers based on the binding relationship between routing keys and queues

Exchange has four types: direct (default), fanout, topic, and headers:

diract: Perfect matching strategy, the routing key of the switch must be completely consistent with the routing key in the binding before sending messages to the corresponding message queue, point-to-point mode;

fanout: Broadcasting strategy, which does not match routing keys and sends messages to all queues bound to the switch, is the fastest because it does not match routing keys.

Topic: The wildcard matching topic policy, in which the switch assigns the routing key properties of the message through pattern matching, matches the routing key to a pattern, where the queue needs to be bound to a pattern. It splits the strings of routing keys and binding keys into words separated by dots. It also recognizes two wildcards: the symbol "" and the symbol "*". # Match 0 or more words, * match one word

headers: Basically not. It matches the header in the message, not the matching routing key. It has poor performance.

Queue: Message queue

Binding: Binding relationship, used to represent the association between a bound switch and a queue. A switch can specify multiple queues, or it can be a many-to-many relationship.

Routing key: The key of the routing key matches the binding relationship to the switch and queue

Channel :

A separate two-way data flow channel in multiplexing connections. Channel is a virtual connection built in a real TCP connection. AMQP commands are sent through the channel. Whether they are publishing messages, subscribing queues or receiving messages, these actions are completed through the channel. Because it is very expensive for the operating system to establish and destroy TCP, the concept of channel is introduced to reuse a TCP connection.

Consumer: Message Consumer

Virtual Host: A virtual host that represents a batch of switches, message queues, and related objects. Virtual hosts are independent server domains that share the same authentication and encryption environment. Each vhost is essentially a mini version of RabitMQ server with its own queue, switch, binding and privilege mechanism. vhost is the basis of AMQP concept and must be specified at connection time. The default vhost of RabbitMQ is /.

Broker: Represents a message queue server entity, which is a rabbitmq server

1. Simple installation using docker

Retrieve Mirror Files

(If you don't have a domestic image, use registry.docker-cn.com/library/rabbitmq to configure an endoscopic image address, and use rabbitmq directly)

docker pull registry.docker-cn.com/library/rabbitmq

start-up

docker -d --name myrabbitmq -p 5672:5672 -p 15672:15672  registry.docker-cn.com/library/rabbitmq

Configure access to web pages

Enter the container

docker exec -it  b198e5bff969 /bin/bash

Start the web management module command as follows (in addition rabbitmq many commands, Baidu can know)
rabbitmqctl start_app
rabbitmq-plugins enable rabbitmq_management

Access ip:15672

Account password guest: guest

Use springboot for integration

amqpAdmin in spring boot encapsulates system operations on switches, queues, etc. rabbitmqTemplate encapsulates the sending and receiving of messages.

Add dependency

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

Configure rabbitmq address

Writing configuration classes

/**
 * Created by Administrator on 2018/11/30.
 *Automatic Configuration Class RabbitAutoConfiguration
 *    The rabbit Tamplate Caching Connection Factory Rabbit Connection FactoryBean is injected into it.
 *      AmqpAdmin System Management Component
 *  RabbitProperties Encapsulated rabbitmq configuration
 *@EnableRabbit  // Turn on automatic configuration of rabbitmq
 */
@EnableRabbit  // Turn on automatic configuration of rabbitmq
@Configuration
public class MyRabbitmqConfig {


}

Manually add a switch exchanges to the page

Switch of direct policy

Switcher for fanout policy

topic Policy Switch

Add message queue

Binding switches and message queues

Writing Message Sender Server Code

    @Test
    public void send() {
        // The routing key defaults to the queue name
        Map map = new HashMap();
        map.put("123","123");
        map.put("lists",new int[]{1,2,3});
        rabbitTemplate.convertAndSend("xiaodu.direct","key01",map);
    }

 

View rabbitmq management page

 

If the object is being transmitted, the message is the result of object serialization

 

Accept code

    @Test
    public void receive() {
//        The parameter is the name of the queue, and the message received can be automatically deserialized back. (Note the implementation of the serialization interface)
//        Messages are automatically deleted when they are taken out
        Object o = rabbitTemplate.receiveAndConvert("xiaodu.queue01");
        System.out.println("Received the message as follows==" + o);
    }

Serialization rules

In spring boot, SimpleMessageConverter is automatically used as the jdk serialization rule by default

Configure in the configuration class using message Converter converted to json

  

The content Payload in the body of the post-use effect message is of json type, not the result of serialization of stored objects.

Test broadcast mode: Broadcast mode does not specify routing keys, but remember to bind switches to the queues you need

Use listening to get messages in the queue: Use the annotation @RabbitListener (note to add @EnableRabbit to the startup class by opening the rabbitmq configuration)

@Service
public class RabbitmqService {

    @RabbitListener(queues = "xiaodu.queue01")
    public void receive(User user) {
        System.out.println("The news that was monitored was = " + user);

    }

}

    //Getting message content using parameter Message
    @RabbitListener(queues = "xiaodu.queue01")
    public void receive02(Message message) {
        byte[] body = message.getBody();
        System.out.println("The content of the message received = " + new String(body));
        MessageProperties messageProperties = message.getMessageProperties();
        System.out.println("Received news headers= " + messageProperties);
    }

Use AmqpAdmin to create switches, queues, binding relationships, etc.

1 Create Exchange

Different switches, queues, and binding relationships can be created according to different strategies

    @Autowired
    private AmqpAdmin amqpAdmin;

    /**
     * Establish
     */
    @Test
    public void createExchange() {
//        Parameter switch name, durable persistence, autoDelete deletion
        Exchange exchange = new DirectExchange("exchange.direct",true,false);
        amqpAdmin.declareExchange(exchange);
//        Create queue-01 queues
        amqpAdmin.declareQueue(new Queue("queue-01"));
//        Create binding relationships
//         The destination of destination binding, the type of Binding. Destination Type destination Type binding is switch or queue.
//         String exchange is bound to that switch, String routing Key, Map < String, Object > arguments command parameters
        Binding binding = new Binding("queue-01",Binding.DestinationType.QUEUE,
               "exchange.direct","exkey-01",null );
        amqpAdmin.declareBinding(binding);

    }

Other operations are similar, you can register your switch directly in the configuration file. Queue, etc.

Reprint rabbitmq distributed: https://blog.csdn.net/gokeiryou263/article/details/54312094

 

Topics: RabbitMQ Docker Spring JSON