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.异步确认发布

相关推荐
starzy199014 小时前
Structured Streaming Kafka Sink:写出一条生产级的回流链路
大数据·分布式·spark·kafka
青石路14 小时前
不依赖 Spring,你会如何自实现 RabbitMQ 消息的消费(二)
后端·rabbitmq
国科安芯19 小时前
编队不是多放几颗星:分布式雷达与编队飞行任务中星内协同网络的确定性时序
网络·分布式·fpga开发·架构·低轨卫星·抗辐射
AllData公司负责人2 天前
实战一:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 File 到 Doris 高效数据同步链路,批量文件离线入仓
数据库·人工智能·分布式·大模型·数据传输·数据同步·连接器
starzy19902 天前
Structured Streaming 集成 Kafka 实现:读写路径、位点语义与生产调优
大数据·分布式·spark·kafka
真上帝的左手3 天前
30. 技术专题-‌应用框架组件-消息队列
分布式·中间件·消息队列·系统架构·mq
真上帝的左手4 天前
31. 占位-14
分布式·spring cloud·架构·系统架构
TiDB 社区干货传送门4 天前
当向量走向百亿规模:平凯数据库对下一代分布式向量索引的探索
数据库·分布式
starzy19904 天前
Structured Streaming Sink 种类与案例:选错输出端,前面全白干
大数据·分布式·spark
Lansonli5 天前
大数据Spark(九十三):Spark HistoryServer
大数据·分布式·spark