1.添加基础配置
添加依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId></dependency>
添加rabbitmq服务配置
spring:rabbitmq:username: guestpassword: guesthost: localhostport: 5672
获取配置值
@Value("${spring.rabbitmq.addresses}")private String hosts;@Value("${spring.rabbitmq.username}")private String userName;@Value("${spring.rabbitmq.password}")private String password;@Value("${spring.rabbitmq.virtual-host}")private String virtualHost;
对于发送方而言,需要做以下配置:
- 配置CachingConnectionFactory
 - 配置Exchange/Queue/Binding
 - 配置RabbitAdmin创建上一步的Exchange/Queue/Binding
 - 配置RabbitTemplate用于发送消息,RabbitTemplate通过CachingConnectionFactory获取到Connection,然后想指定Exchange发送
 
对于消费方而言,需要做以下配置:
- 配置CachingConnectionFactory
 - 配置Exchange/Queue/Binding
 - 配置RabbitAdmin创建上一步的Exchange/Queue/Binding
 - 配置RabbitListenerContainerFactory
 - 配置@RabbitListener/@RabbitHandler用于接收消息
 
在默认情况下主要的配置如下:
| 配置项 | 默认值 | 作用 | 
|---|---|---|
| host | localhost | RabbitMQ服务器地址 | 
| port | 5672 | RabbitMQ服务器端口 | 
| username | 账户名 | guest | 
| password | 密码 | guest | 
| virtualHost | RabbitMQ虚拟主机名 | / | 
| publisherConfirms | false | 设置是否启用生产方确认 | 
| publisherReturns | false | 设置是否启用生产方消息返回 | 
| ssl | 对象 | 配置SSL,默认停用 | 
| template | 对象 | 设置RabbitTemplate | 
| template.retry | 默认停用 | 设置RabbitTemplate发送消息时的重试,主要用于RabbitTemplate与RabbitMQ之间的网络连接 | 
| template.mandatory | false | 设置发送消息失败时(无接收queue)是否return 消息,与return callback一并使用 | 
| template.exchange | “” | 默认发送的exchange | 
| template.routingKey | “” | 默认发送消息时的routing key | 
| template.defaultReceiveQueue | null | 默认接收消息的queue | 
| listener.simple | 对象 | 设置SimpleRabbitListenerContainerFactory | 
| listener.direct | 对象 | 设置DirectRabbitListenerContainerFactory | 
| listener.simple.concurrency | null | 并发消费方数量 | 
| listener.simple.acknowledgeMode | AUTO | 设置消费方确认模式,这里的AUTO与RabbitMQ的自动确认不是一回事 | 
| listener.simple.prefetch | 250 | 设置消费方一次性接收消息的条数 | 
| listener.simple.defaultRequeueRejected | true | 当Listener发生异常时是否requeue | 
| listener.simple.retry | 对象 | 设置Listener的重试机制,默认停用,当启用时,Listener对于消息处理过程中的异常将进行requeue重试,超过重试次数再抛弃,此时AmqpRejectAndDontRequeueException异常也会被重试 | 
[
](https://blog.csdn.net/qq_45491757/article/details/105712530)
