RabbitMQ - 发布确认

1.发布确认的策略

复制代码
//开启发布确认
channel.confirmSelect();

2.单个确认发布

复制代码
/**
 * 单个发送
 */
public static void publishMessageIndividually() throws Exception {
    Channel channel = RabbitMqUtils.getChannel();
    //队列声明
    String queueName = UUID.randomUUID().toString();
    channel.queueDeclare(queueName, true, false, false, null);
    //开启发布确认
    channel.confirmSelect();

    long begin = System.currentTimeMillis();

    for (int i = 0; i < MESSAGE_COUNT; i++) {
        String message = i + "";
        channel.basicPublish("", queueName, null, message.getBytes());
        //服务端返回 false 或超时时间内未返回,生产者可以消息重发
        boolean flag = channel.waitForConfirms();
        if (flag) {
            System.out.println("消息发送成功");
        }
    }

    long end = System.currentTimeMillis();
    System.out.println("发布" + MESSAGE_COUNT + "个单独确认消息,耗时" + (end - begin) + "ms");

}

3.批量确认发布

复制代码
/**
 * 批量
 */
public static void publishMessageBatch() throws Exception {
    Channel channel = RabbitMqUtils.getChannel();
    //队列声明
    String queueName = UUID.randomUUID().toString();
    channel.queueDeclare(queueName, true, false, false, null);
    //开启发布确认
    channel.confirmSelect();
    //批量确认消息大小
    int batchSize = 100;
    //未确认消息个数
    int outstandingMessageCount = 0;
    long begin = System.currentTimeMillis();

    for (int i = 0; i < MESSAGE_COUNT; i++) {
        String message = i + "";
        channel.basicPublish("", queueName, null, message.getBytes());
        outstandingMessageCount++;
        if (outstandingMessageCount == batchSize) {
            channel.waitForConfirms();
            outstandingMessageCount = 0;
        }
    }
    //为了确保还有剩余没有确认消息 再次确认
    if (outstandingMessageCount > 0) {
        channel.waitForConfirms();
    }
    long end = System.currentTimeMillis();
    System.out.println("发布" + MESSAGE_COUNT + "个批量确认消息,耗时" + (end - begin) + "ms");
}

4.异步确认发布

相关推荐
做个文艺程序员2 天前
私有 LLM 多机多卡分布式推理:Pipeline Parallel vs Tensor Parallel 踩坑全记录
人工智能·分布式
foundbug9992 天前
Matlab基于分布式模型预测控制的多固定翼无人机共识控制
分布式·matlab·无人机
一个有温度的技术博主2 天前
Redis集群实战:如何实现节点的弹性伸缩与数据迁移?
redis·分布式·缓存·架构
小雨青年2 天前
鸿蒙 HarmonyOS 6 | 分布式数据同步详解
分布式·华为·harmonyos
2501_933329552 天前
Infoseek舆情监测系统:基于大模型与多模态AI的品牌公关中台架构设计与实现
人工智能·分布式·自然语言处理·架构
小红的布丁2 天前
MySQL 和 Redis 数据一致性,以及 Redis 与 ZooKeeper 分布式锁对比
redis·分布式·mysql
qq_396227952 天前
Git 分布式版本控制
分布式·git
富士康质检员张全蛋2 天前
Kafka JMS
分布式·kafka
心勤则明2 天前
Spring AI Alibaba 分布式智能体实战:基于 A2A 协议的架构演进与落地
人工智能·分布式·spring
开心码农1号2 天前
mq是什么,常用mq的使用场景有哪些?
中间件·rabbitmq