件,通过RabbitMQ可以帮助我们实现异步、削峰的目的。
今天这篇,我们来看看Spring Boot是如何集成RabbitMQ,发送消息和消费消息的。同时我们介绍下死信队列。
集成RabbitMQ
集成RabbitMQ只需要如下几步即可
1、添加maven依赖
<!--rabbitmq--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> 2、添加配置文件application.yaml
在application.yaml添加配置内容如下
spring: rabbitmq: host: 192.168.1.161 port: 5672 username: guest password: guest cache: channel: size: 10 listener: type: simple simple: acknowledge-mode: auto concurrency: 5 default-requeue-rejected: true max-concurrency: 100 retry: enabled: true # initial-interval: 1000ms max-attempts: 3 # max-interval: 1000ms multiplier: 1 stateless: true # publisher-confirms: true</pre> 注意:
这里最基本的配置只需要配置host,port,username和password四个属性即可
其他属性都有各自的含义,比如retry是用于配置重试策略的,acknowledge-mode是配置消息接收确认机制的。
3、编写配置类
编写RabbitConfig配置类,采用Java Configuration的方式配置RabbitTemplate、Exchange和Queue等信息,具体如下所示
package com.jackie.springbootdemo.config; import org.springframework.amqp.core.*; import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import java.util.HashMap; import java.util.Map; @Configuration public class RabbitMQConfig implements InitializingBean { @Autowired SimpleRabbitListenerContainerFactory simpleRabbitListenerContainerFactory; @Override public void afterPropertiesSet() throws Exception { simpleRabbitListenerContainerFactory.setMessageConverter(new Jackson2JsonMessageConverter()); } @Bean("jackson2JsonMessageConverter") public Jackson2JsonMessageConverter jackson2JsonMessageConverter(ConnectionFactory connectionFactory) { return new Jackson2JsonMessageConverter(); } @Bean("rabbitTemplate") @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory, @Qualifier("jackson2JsonMessageConverter") Jackson2JsonMessageConverter jackson2JsonMessageConverter) { RabbitTemplate template = new RabbitTemplate(connectionFactory
