rabbitMQ生产者的异步的异步批量发布确认demo

java 复制代码
    //批量发布异步确认
    public static void publishSync() throws Exception {
         //创建链接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();

        //设置链接
        connectionFactory.setHost("192.168.43.37");
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");

        //链接工厂创建链接
        Connection connection = connectionFactory.newConnection();

        //获取信道
        Channel channel = connection.createChannel();

        //信道声明
        String queueName = UUID.randomUUID().toString();
        channel.queueDeclare(queueName, true, false, false, null);

        //开启发布确认
        channel.confirmSelect();


        /**
         * 线程安全有序的一个哈希表 适用于高并发的情况下
         *
         * 1.轻松的将需要与消息进行关联
         * 2.轻松的批量删除条数
         * 3.支持高并发
         */
        ConcurrentSkipListMap<Long,String> outstandingConfirms = new ConcurrentSkipListMap<>();



        //确认监听器
        ConfirmCallback confirmCallback = ( deliveryTag,multiple)->{
            System.out.println("消息确认监听器成功确认:" +  deliveryTag);
            //删除发送过的消息
            if(multiple){
                //批量的删除确认的消息 剩下的是未确认的
                ConcurrentNavigableMap<Long,String> confirmed =
                        outstandingConfirms.headMap(deliveryTag);
                confirmed.clear();

            }else {
                outstandingConfirms.remove(deliveryTag);
            }

        };

        ConfirmCallback nconfirmCallback= ( deliveryTag,multiple)->{

            //未确认的消息
            String message = outstandingConfirms.get(deliveryTag);
            System.out.println("未确认的消息:"+deliveryTag +"-"+message);

        };

        channel.addConfirmListener(confirmCallback,nconfirmCallback);


        //开始时间
        long begin = System.currentTimeMillis();
        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String mes = i + "";
            channel.basicPublish("",queueName,null,mes.getBytes("UTF-8"));
            outstandingConfirms.put(channel.getNextPublishSeqNo(),mes);

            //记录所有发布的消息
        }

        long end = System.currentTimeMillis();
        System.out.println("发布"+MESSAGE_COUNT+"条用时共计:" + (end-begin) );

    }
相关推荐
爱敲键盘的猴子2 小时前
MQ高级 -- RabbitMQ
rabbitmq
ttghgfhhjxkl2 小时前
Windows 系统下 RabbitMQ 延迟插件的安装步骤与常见问题修复
windows·rabbitmq·ruby
即兴随缘3 小时前
【RabbitMQ】RPC模式(请求/回复)
rabbitmq·.net
꒰ঌ 安卓开发໒꒱4 小时前
RabbitMQ面试全解析:从核心概念到高可用架构
面试·架构·rabbitmq
做运维的阿瑞4 小时前
用 Python 构建稳健的数据分析流水线
开发语言·python·数据分析
左师佑图4 小时前
综合案例:Python 数据处理——从Excel文件到数据分析
开发语言·python·数据分析·excel·pandas
l1t6 小时前
利用DeepSeek修改数据结构提升求解集合程序效率
数据结构·python·deepseek
jiushun_suanli6 小时前
PyTorch CV模型实战全流程(一)
人工智能·pytorch·python
2301_764441336 小时前
基于python构建的低温胁迫实验
开发语言·python
天才测试猿6 小时前
Selenium定位元素的方法css和xpath的区别
css·自动化测试·软件测试·python·selenium·测试工具·测试用例