rabbitmq发布确认
生产者将信道设置成 confirm 模式,一旦信道进入 confirm 模式,所有在该信道上面发布的 消息都将会被指派一个唯一的 ID(从 1 开始),一旦消息被投递到所有匹配的队列之后,broker 就会发送一个确认给生产者(包含消息的唯一 ID),这就使得生产者知道消息已经正确到达目的队 列了,如果消息和队列是可持久化的,那么确认消息会在将消息写入磁盘之后发出,broker 回传 给生产者的确认消息中 delivery-tag 域包含了确认消息的序列号,此外 broker 也可以设置 basic.ack 的 multiple 域,表示到这个序列号之前的所有消息都已经得到了处理。
confirm 模式最大的好处在于他是异步的,一旦发布一条消息,生产者应用程序就可以在等信 道返回确认的同时继续发送下一条消息,当消息最终得到确认之后,生产者应用便可以通过回调 方法来处理该确认消息,如果 RabbitMQ 因为自身内部错误导致消息丢失,就会发送一条 nack 消 息,生产者应用程序同样可以在回调方法中处理该 nack 消息
开启发布确认的方式
发布确认默认是没有开启的,如果要开启需要调用方法 confirmSelect,每当你要想使用发布 确认,都需要在 channel 上调用该方法
channel.confirmSelect();
单个消息的发布确认
这是一种简单的确认方式,它是一种同步确认发布的方式,也就是发布一个消息之后只有它 被确认发布,后续的消息才能继续发布,waitForConfirmsOrDie(long)这个方法只有在消息被确认 的时候才返回,如果在指定时间范围内这个消息没有被确认那么它将抛出异常。
这种确认方式有一个最大的缺点就是:发布速度特别的慢,因为如果没有确认发布的消息就会 阻塞所有后续消息的发布,这种方式最多提供每秒不超过数百条发布消息的吞吐量。当然对于某 些应用程序来说这可能已经足够了。
/**
* 单个发布确认
*/
public class SingleConfirmProducer {
public static void main(String[] args) throws IOException, InterruptedException {
Channel channel = RabbitUtil.getChannel();
channel.queueDeclare(QueueNames.SINGLE_CONFIRM,false,false,false,null);
//开启发布确认
channel.confirmSelect();
long begin = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
String message = i+"";
channel.basicPublish("",QueueNames.SINGLE_CONFIRM,null,message.getBytes(StandardCharsets.UTF_8));
//服务端返回false或者超市时间内未返回,生产者可以重新发送消息
boolean result = channel.waitForConfirms();
if (result){
System.out.println(message +"这个消费发送成功");
}
}
long end = System.currentTimeMillis();
System.out.println("发布100个单独确认消息,耗时"+(end - begin) +"ms" );
}
}
批量消息的发布确认
上面那种方式非常慢,与单个等待确认消息相比,先发布一批消息然后一起确认可以极大地 提高吞吐量,当然这种方式的缺点就是:当发生故障导致发布出现问题时,不知道是哪个消息出现 问题了,我们必须将整个批处理保存在内存中,以记录重要的信息而后重新发布消息。当然这种 方案仍然是同步的,也一样阻塞消息的发布。
/**
* 发布确认 批量确认
*/
public class BatchConfirmProducer {
public static void main(String[] args) throws InterruptedException, IOException {
Channel channel = RabbitUtil.getChannel();
channel.queueDeclare(QueueNames.BATCH_CONFIRM,false,false,false,null);
channel.confirmSelect();
int batchSize = 100;
int unConfirmCount = 0;
long begin =System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
String message = i+"";
channel.basicPublish("",QueueNames.BATCH_CONFIRM,null,message.getBytes(StandardCharsets.UTF_8));
unConfirmCount++;
if (unConfirmCount == batchSize){
channel.waitForConfirms();
unConfirmCount = 0;
}
}
if (unConfirmCount >0){
channel.waitForConfirms();
}
long end = System.currentTimeMillis();
System.out.println("发布10000个单独确认消息,耗时"+(end - begin) +"ms" );
}
}
异步确认发布
异步确认虽然编程逻辑比上两个要复杂,但是性价比最高,无论是可靠性还是效率都没得说, 他是利用回调函数来达到消息可靠性传递的,这个中间件也是通过函数回调来保证是否投递成功。
/**
* 异步发布确认
*/
public class AsynConfirmProducer {
public static void main(String[] args) throws IOException {
Channel channel = RabbitUtil.getChannel();
channel.queueDeclare(QueueNames.ASYN_CONFIRM,false,false,false,null);
//开启发布确认
channel.confirmSelect();
ConcurrentSkipListMap<Long, String> outstandingConfirms = new ConcurrentSkipListMap<>();
/*
* 确认收到消息的回调
* long deliveryTag:消息的序列号
* boolean multiple:
* true:小于等于当前序列号的消息
* false:如果为false,那么就是当前序列号消息
*
*/
ConfirmCallback ackCallback = (deliveryTag, multiple) -> {
if (multiple){
//如果是小于等于当前序列号的消息,那么就清除该部分未确认的消息
ConcurrentNavigableMap<Long, String> confirmed = outstandingConfirms.headMap(deliveryTag, true);
confirmed.clear();
}else {
outstandingConfirms.remove(deliveryTag);
}
};
/*
* 消息未被确认的回调
*/
ConfirmCallback nackCallback = (deliveryTag, multiple) -> {
String message = outstandingConfirms.get(deliveryTag);
System.out.println("发布的消息"+message+"未被确认,序列号"+deliveryTag);
};
/**
* 添加一个异步确认的监听器
* 1。确认收到消息的回调
* 2。未收到消息的回调
*/
channel.addConfirmListener(ackCallback,nackCallback);
long begin = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
String message = "消息"+i;
outstandingConfirms.put(channel.getNextPublishSeqNo(),message);
channel.basicPublish("",QueueNames.ASYN_CONFIRM,null,message.getBytes(StandardCharsets.UTF_8));
}
long end = System.currentTimeMillis();
System.out.println("发布10000个单独确认消息,耗时"+(end - begin) +"ms" );
}
}
springboot中消息确认
配置文件中需要添加
spring.rabbitmq.publisher-confirm-type=correlated
可选值有三个
- none:禁用确认发布模式,是默认值
- correlated:发布消息成功到交换机后会出发回调方法
- simple
- 经测试有两种效果,其一效果和correlated值一样会出发回调方法
- 其二在发布消息成功后使用rabbitTemplate调用waitForConfirms或waitForConfirmsOrDie方法等待broker节点返回发送结果,根据返回结果来判定下一步的逻辑,要注意的点是waitForConfirmsOrDie方法如果返回false则会关闭channel,则接下来无法发送消息到broker
修改配置文件
server.port=8080
spring.rabbitmq.host=172.16.140.133
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=123456
#发布确认
spring.rabbitmq.publisher-confirm-type=correlated
创建配置类
/**
* 发布确认配置类
*/
@Configuration
public class ConfirmConfig {
public static final String CONFIRM_EXCHANGE = "confirm.exchange";
public static final String CONFIRM_QUEUE_NAME = "confirm.queue";
@Bean("confirmExchange")
public DirectExchange confirmExchange(){
return new DirectExchange(CONFIRM_EXCHANGE);
}
@Bean("confirmQueue")
public Queue confirmQueue(){
return QueueBuilder.durable(CONFIRM_QUEUE_NAME).build();
}
@Bean
public Binding queueBinding(@Qualifier("confirmQueue") Queue queue,@Qualifier("confirmExchange") DirectExchange exchange){
return BindingBuilder.bind(queue).to(exchange).with("key1");
}
}
创建消息确认回调接口
/**
* 消息确认回调接口
*/
@Component
@Slf4j
public class MyCallBack implements RabbitTemplate.ConfirmCallback {
@Override
public void confirm(CorrelationData correlationData, boolean ack, String cause) {
String id = correlationData != null ? correlationData.getId():"";
if (ack){
log.info("交换机已经收到id为:{}的消息",id);
}else {
log.info("交换机还未收到id为:{}的消息,由于原因:{}",id ,cause);
}
}
}
创建消息的消费者
/**
* 消息消费者
*/
@Component
@Slf4j
public class ConfirmConsumer {
public static final String CONFIRM_QUEUE_NAME = "confirm.queue";
@RabbitListener(queues = CONFIRM_QUEUE_NAME)
public void receiveMsg(Message message){
String msg = new String(message.getBody());
log.info("接收到队列confirm.queue消息:{}",msg);
}
}
创建消息的生产者
/**
* 消息生产者
*/
@RestController
@RequestMapping("/confirm")
@Slf4j
public class ProducerController {
public static final String CONFIRM_EXCHANGE_NAME = "confirm.exchange";
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
private MyCallBack myCallBack;
/**
* 初始化rabbitTemplate
*/
@PostConstruct
public void init(){
rabbitTemplate.setConfirmCallback(myCallBack);
}
@GetMapping("sendMessage/{message}")
public void sendMessage(@PathVariable String message){
CorrelationData correlationData = new CorrelationData("1");
String routingKey = "key1";
rabbitTemplate.convertAndSend(CONFIRM_EXCHANGE_NAME,routingKey,message+routingKey,correlationData);
CorrelationData correlationData2 = new CorrelationData("2");
String routingKey2 = "key2";
rabbitTemplate.convertAndSend(CONFIRM_EXCHANGE_NAME,routingKey2,message+routingKey,correlationData2);
log.info("发送消息内容:{}",message);
}
}
结果
- 发送了两条消息,第一条的routingkey为key1,第二条消息的routingKey为key2,两条消息都成功被交换机接收,耶收到了交换机的确认回调
- 消费者只收到了一条消息,因为第二条消息的routingkey与队列的bindingkey不一致,也没有其他队列能接受这个消息,所以第二条消息被直接丢弃了。