前言
在消息中间件的实际使用中如何保证消息的可靠性是我们必须要考虑的,因此就需要了解一下Rabbitmq的confirm模式、return模式,以及消费端的手动确认ACK等等了。
1、confirm模式:
此模式是作用在生产端的,开启了这个模式就可以知道消息有木有发送到exchange上。不管有没有发送到都会触发回调方法。
2、return模式:
此模式同样是作用在生产端的,这个模式就是为了知道消息有木有发送到对应的队列上。如果发送到了对应的队列不会触发回调方法,如果没有发送到对应的队列才会触发回调方法。
3、消费端的ACK确认:
这个是作用在消费端的,为了保证消息正确被消费者消费,分为手动确认和自动确认。
自动确认:消息一旦被消费了队列就会立马丢弃,不管你的业务逻辑最后是否正确执行。
手动确认:消息被消费了队列不会立马丢弃,需要手动应答,如果业务逻辑正确执行完成,那么通知队列你可以丢弃了,否则可以让消息再次返回队列处理或者直接丢弃也行。
还是直接上代码吧
代码实现
环境:2个SpringBoot工程(我这里就不搭建了)
1、生产端代码
生产端我直接用Junit来测试发送消息了,结构如下
pom.xml:
<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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
yml配置文件:
spring:
application:
name: rabbitmq-springboot
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest