RabbitMQ study notes (1): installation and Springboot integration

foreword

MQ, the abbreviation of Message Queue.

RabbitMQ is a type of MQ, just like China Merchants Bank is a type of bank. It is mainly used to realize the asynchrony and decoupling of the application , and it can also play the role of message buffering and message distribution.

The main function of message middleware is decoupling . The most standard usage of middleware is that producers produce messages and send them to queues, and consumers take messages from queues and process them. Producers don’t need to care who consumes them, and consumers don’t care Who is producing the message, so as to achieve the purpose of decoupling. In distributed systems, message queues are also used in many other aspects, such as: distributed transaction support, RPC calls, and so on.

Install

1.windows 2.centos
_ _

springboot integration

Simple (one producer, one consumer, using TopicExchange)

MAVEN depends on:

        <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>
            <scope>test</scope>
        </dependency>

application.properties

Adjust according to your configuration

spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

Configure Queue, Exchange and their binding relationships

@Configuration
public class RabbitConfig {

    @Bean
    public Queue commonQueue() {
        return new Queue("commonQueue");
    }

    @Bean
    public TopicExchange commonExchange() {
        return new TopicExchange("topicExchange");
    }

    @Bean
    public Binding commonBinding() {
        return BindingBuilder.bind(commonQueue()).to(commonExchange()).with("topic.unique.key");
    }

}

Here I only configure one queue and bind it to the specified TopicExchange for establishing contact between producers and consumers.

Producer (send message)

Springboot has encapsulated the Rabbit template class RabbitTemplate for us, which can be used to send and receive messages, and can be used directly by injection.
Here we send a date string to the server.

@Component
public class Producer {
    private final RabbitTemplate rabbitTemplate;

    @Autowired
    public Producer(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    public void send() {
        String msg = new Date().toString();
        rabbitTemplate.convertAndSend("topicExchange", "topic.unique.key", msg);
        LoggerFactory.getLogger(this.getClass()).info("消息{}已发送!", msg);
    }
}

Note: The send() method is custom, used for external calls, and can take parameters.

If an external program calls the generator's send method, it can be viewed directly on the server according to exchange and queue.
Test class:

@SpringBootTest
@RunWith(SpringRunner.class)
public class SimpleTest {

    @Autowired
    private Producer producer;

    @Test
    public void testSimple() {
        producer.send();
    }
}

Server effect:

It means that our message was sent successfully, so how to get and process it?

consumer

It is very easy to receive messages in springboot, just add annotations to the method @RabbitListenerand bind the listening queue through queuesparameters. Since we only have one queue in the above example, commonQueuewe bind it and print the received message:

@Component
public class Consumer extends RabbitProperties.Listener {
    private static final Logger LOGGER = LoggerFactory.getLogger(Consumer.class);
    private static final String COMMON_QUEUE = "commonQueue";

    @RabbitListener(queues = COMMON_QUEUE)
    public void dealMessageOfCommonQueue(String msg) {
        LOGGER.info("接收到来自队列{}的消息:{}", COMMON_QUEUE, msg);
    }
}

Start the service to see if you can get the string just sent from the server:

if you see the message printed, it means that it was successfully consumed. If you go to the server to check it again, you will find that the message is empty because it has been consumed. .

Notice:

  • In the method of processing the message, a String type parameter is passed in, because it is clear that the message sent by the producer is of the string type. It can also be other types, as long as it is right.
  • If it is received with the Object type, it will pass in some configuration information in addition to the message sent by the sender. Therefore, it is not recommended to use Object as a parameter.
  • Here, for the convenience of demonstration, the producer and the consumer are written in one service, they can be in different (micro) services, the 解耦two words in the preface should be thought of here.

refer to

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324936603&siteId=291194637