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

    }
相关推荐
顾安r2 小时前
11.20 开源APP
服务器·前端·javascript·python·css3
萧鼎2 小时前
Python PyTesseract OCR :从基础到项目实战
开发语言·python·ocr
q***23572 小时前
RabbitMQ介绍以及基本使用
qt·rabbitmq·ruby
没有bug.的程序员3 小时前
Java 字节码:看懂 JVM 的“机器语言“
java·jvm·python·spring·微服务
下午见。5 小时前
Python基础入门:用Anaconda搭建环境的启蒙之旅
python
这人很懒没留下什么6 小时前
SpringBoot2.7.4整合RabbitMq
rabbitmq·springboot
我叫汪枫6 小时前
Python 办公自动化入门:玩转 Excel 与 Word
python·word·excel
E_ICEBLUE6 小时前
三步完成 Markdown 到 Word/PDF 的转换:Python 教程
python·pdf·word·markdown·格式转换
zl9798996 小时前
RabbitMQ-Work Queues
分布式·rabbitmq
后台开发者Ethan7 小时前
LangGraph ReAct应用
python·langgraph