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

    }
相关推荐
SaleCoder43 分钟前
用Python构建机器学习模型预测股票趋势:从数据到部署的实战指南
开发语言·python·机器学习·python股票预测·lstm股票模型·机器学习股票趋势
技术猿188702783517 小时前
实现“micro 关键字搜索全覆盖商品”并通过 API 接口提供实时数据(一个方法)
开发语言·网络·python·深度学习·测试工具
烛阴7 小时前
为什么你的Python项目总是混乱?层级包构建全解析
前端·python
三金C_C7 小时前
asyncio 与 uvloop
python·异步·asyncio
放飞自我的Coder7 小时前
【colab 使用uv创建一个新的python版本运行】
开发语言·python·uv
黎茗Dawn8 小时前
连接new服务器注意事项
linux·python
LJianK18 小时前
Java和JavaScript的&&和||
java·javascript·python
天天爱吃肉821810 小时前
效率提升新范式:基于数字孪生的汽车标定技术革命
python·嵌入式硬件·汽车
lemon_sjdk11 小时前
Java飞机大战小游戏(升级版)
java·前端·python
格鸰爱童话11 小时前
python+selenium UI自动化初探
python·selenium·自动化