This is the 16th day of my participation in the August More Text Challenge. For details, see:August is more challenging

Include a column

Spring Boot quick start

Java full stack Architect

Initial the RabbitMQ

RabbitMQ is open source message broker software (also known as message Oriented middleware) that implements the Advanced Message Queuing Protocol (AMQP). RabbitMQ servers are written in the Erlang language, and clustering and failover are built on the Open Telecom Platform framework. All major programming languages have client libraries that communicate with proxy interfaces.

The RabbitMQ advantage

  • Reliability: persistence, transmission confirmation, and release confirmation.
  • Flexible Routing
  • Message Clustering
  • Highly Available Queues
  • Multi-protocol: Supports multiple message queue protocols, such as STOMP, MQTT, and so on.
  • Many Clients: Support for almost all common languages Java,.NET, Ruby, and so on.
  • Management UI: Users can monitor and manage many aspects of the message Broker.
  • Tracing mechanism
  • Plugin System: Many lookups for easy extension

The RabbitMQ role

Synchronous mutation step

In the process of placing an order, such as a dongzhong, after placing an order, if wechat message push and email sending are opened.

High cohesion and low coupling

When multiple systems interact with each other, in order to be independent of each other and to communicate normally, the push service system only needs to subscribe to the information published by the order service system on RabbitMQ and complete the push service.

Traffic peak clipping

If a large number of requests are made to the service system, the server may crash if the number of requests is not controlled, so add a new RabbitMQ message queue in the middle and put the requested data directly into the message queue. The queued requests are then sent in turn to the business system for business processing. Common scenarios include: Seckill system,

Quick start

POM

This time, Maven is used to build the project, so POM dependencies are introduced. Two are required to import Maven dependencies, as shown below.

<! -- RabbitMQ strat--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> <dependency> <groupId>org.springframework.amqp</groupId>  <artifactId>spring-rabbit-test</artifactId> <scope>test</scope> </dependency> <! -- RabbitMQ end-->Copy the code

application.properties

Import the basic RabbitMQ configuration information in the application.properties file. The simplest configuration information includes the RabbitMQ host address, port number, and basic user name and password.

Rabbitmq. host=127.0.0.1 spring.rabbitmq.port=5672 spring.rabbitmq.username=admin spring.rabbitmq.password=adminCopy the code

RabbitMqConfig

RabbitMQ configuration, mainly to configure the queue, if the queue already exists, can omit this configuration class.

  • Exchange: A message Exchange that specifies which queues messages are routed to according to which rules.
  • Queue: The carrier of messages to which each message is placed. Durable: durable; exclusive: exclusive.
  • Binding: Binds an Exchange to a queue according to routing rules.
  • Broker: A transport service whose role is to maintain a route from the producer to the consumer, ensuring that data is transmitted in the specified manner.

RabbitMqConfig binds switches, queues, and routes by keyword. A single switch can bind multiple message queues, meaning messages pass through a single switch

package com.example.demo.config; import com.example.demo.constant.RabbitConstant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.BindingBuilder; import org.springframework.amqp.core.DirectExchange; import org.springframework.amqp.core.Queue; import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.context.annotation.Bean; /** * @ClassName RabbitMqConfig * @Description: RabbitMQ configuration * @author JavaZhan @public :Java full stack Architect * @date 2020/6/12 * @version V1.0 **/ @slf4j public class RabbitMqConfig { @Bean public RabbitTemplate rabbitTemplate(CachingConnectionFactory connectionFactory) { connectionFactory.setPublisherReturns(true); RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory); rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter()); rabbitTemplate.setMandatory(true); rabbitTemplate.setConfirmCallback((correlationData, ack, Cause) -> log.info(" Message sent successfully :correlationData({}),ack({}),cause({})"); rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, Message loss: Exchange ({}),route({}),replyCode({}),replyText({}), Message :{}", Exchange, routingKey, replyCode, replyText, message)); return rabbitTemplate; } @Bean public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); factory.setConnectionFactory(connectionFactory); factory.setMessageConverter(new Jackson2JsonMessageConverter()); return factory; } @bean public Queue testQueue() {return new Queue(rabbitconstant.test_queue); /** * switch ** / @bean public DirectExchange testExchange() {return new DirectExchange(RabbitConstant.TEST_QUEUE_KEE_EXCHANGE, true, false); } /** * Queue Binding route and switch ** / @bean public Binding taskOrderHandleBinding() {return BindingBuilder.bind(testQueue()).to(testExchange()).with(RabbitConstant.TEST_QUEUE_KEY); }}Copy the code

Message consumer

/** * @ClassName TestConsumer * @Description: @date 2020/6/12 * @version V1.0 **/ @Component public class TestConsumer {@author JavaZhan :Java full stack Architecture * @date 2020/6/12 * @version V1.0 **/ @Component public class TestConsumer { @RabbitListener(bindings = @QueueBinding( value = @Queue(value = RabbitConstant.TEST_QUEUE), key = RabbitConstant.TEST_QUEUE_KEY, exchange = @Exchange(value = RabbitConstant.TEST_QUEUE_KEE_EXCHANGE) )) @RabbitHandler() public void getMsg(String messageBody, Message message, Channel channel) throws Exception { System.out.println(messageBody); }}Copy the code

Message producer

/** * @className message producer * @description: TODO * @author JavaZhan @java full stack Architect * @date 2020/6/12 * @version V1.0 **/ @Component public class TestSender { @Autowired private RabbitTemplate rabbitTemplate; public void send(String str){ rabbitTemplate.convertAndSend(RabbitConstant.TEST_QUEUE_KEE_EXCHANGE,RabbitConstant.TEST_QUEUE_KEY,str); }}Copy the code

RabbitConstant

Basic RabbitMq configuration information, which can include multiple switches, queues and routes.

package com.example.demo.constant; /** * @ClassName RabbitConstant * @Description: TODO * @author JavaZhan @public :Java full stack architect * @date 2020/6/12 * @version V1.0 **/ public interface RabbitConstant {/** ** * */ String TEST_QUEUE ="TEST_QUEUE"; /** * test route ** / String TEST_QUEUE_KEY ="TEST_QUEUE_KEY"; /** * test switch ** / String TEST_QUEUE_KEE_EXCHANGE ="TEST_QUEUE_KEY_EXCHANGE"; }Copy the code

The test class

@Test void testMqSendMsg(){ for(int i =0 ; i<20; I ++){testSender. Send (" this is the message "+ I +" this is a test message! From [Nuggets, Jacks] "); }}Copy the code

Starting local MQ

As shown in the figure below, RabbitMQ has been started and logged in properly.

After running the test case, output

Well, a simple Spring Boot integration to RabbitMQ is set up.

conclusion

So the integration of RabbitMQ and Spring Boot is successful. For more tests, you can delve into the high availability of RabbitMQ cluster configurations.

Author introduction: [little ajie] a love to tinker with the program ape, JAVA developers and enthusiasts. Public account [Java full stack architect] maintainer, welcome to pay attention to reading communication.

Well, thank you for reading, I hope you like it, if it is helpful to you, welcome to like the collection. If there are any shortcomings, please comment and correct them. See you next time.

Recommended Reading:

My first Spring Boot project has started!

【Spring Boot Quick Start 】 two, weekend set up Spring Boot column, welcome to learn and communicate

【Spring Boot quick Start 】 3, Spring Boot integrated MyBatis, can connect to the database!

【Spring Boot Quick Start 】 four, Spring Boot integration JUnit

【Spring Boot Quick Start 】 5, Spring Boot integrated Swagger UI

【Spring Boot quick Start 】 6, Spring Boot integration Lombok

【Spring Boot quick Start 】 7, Spring Boot integrated Redis