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) );

    }
相关推荐
2401_823943202 分钟前
如何从Python初学者进阶为专家?
jvm·数据库·python
l1t3 分钟前
DeepSeek辅助测试不同文件格式的读写性能和大小
数据库·人工智能·python
2301_818419014 分钟前
用Python和Twilio构建短信通知系统
jvm·数据库·python
2401_873204655 分钟前
使用Docker容器化你的Python应用
jvm·数据库·python
烟花巷子7 分钟前
使用Python进行网络设备自动配置
jvm·数据库·python
陈振wx:zchen200813 分钟前
Python
python
测试199816 分钟前
Jmeter接口测试:使用教程(上)
自动化测试·python·测试工具·jmeter·职场和发展·测试用例·接口测试
七夜zippoe17 分钟前
量子计算入门:Qiskit框架实战
python·算法·量子计算·ibm·qiskit
Zhansiqi20 分钟前
day45
python
telllong20 分钟前
Termux:在手机上跑Python AI应用的真实体验
人工智能·python·智能手机