版本说明
- spring-rabbit:1.7.3.RELEASE
- spring-context:4.3.9.RELEASE
pom.xml引入
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>${org.spring-rabbit.version}</version>
</dependency>
spring配置
<rabbit:connection-factory id="connectionFactory"
host="${rabbit.host}"
port="${rabbit.port}"
username="${rabbit.username}"
password="${rabbit.password}"
publisher-confirms="true"
/>
<rabbit:admin connection-factory="connectionFactory" />
<!-- 给模板指定转换器 -->
<rabbit:template id="amqpTemplate" exchange="mq-exchange"
connection-factory="connectionFactory"
confirm-callback="comfirmCallBackListener"
return-callback="returnCallBackListener"
mandatory="true"
message-converter="jsonMessageConverter"/>
<!-- 队列申明 -->
<rabbit:queue name="queue.hello" />
<!-- 申明交换机,通过routingkey绑定队列 -->
<rabbit:direct-exchange name="mq-exchange" id="mq-exchange">
<rabbit:bindings>
<rabbit:binding queue="queue.hello" key="hello" />
</rabbit:bindings>
</rabbit:direct-exchange>
<!-- 配置consumer, 监听的类和queue的对应关系 -->
<rabbit:listener-container connection-factory="connectionFactory" >
<!-- 下面的queue可以写多个 用,号隔开 -->
<rabbit:listener queues="queue.hello" ref="receiveLitener"/>
</rabbit:listener-container>
1、durable=”true” 说明:
如果加到<rabbit:direct-exchange>
标签中,rabbitmq服务器重启后,申明exchange丢失。
如果加到<rabbit:queue>
标签中,rabbitmq服务器重启后,申明的队列以及数据全部丢失。
2、消息确认配置
publisher-confirms="true"
mandatory="true"
测试结果:
*如果消息没有到exchange,则confirm回调,ack=false
如果消息到达exchange,则confirm回调,ack=true
exchange到queue成功,则不回调return
exchange到queue失败,则回调return(需设置mandatory=true,否则不回回调,消息就丢了)*