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 小时前
在Python 2.7中安装SQLAlchemy的完整指南
开发语言·python·ai写作
电商数据girl2 小时前
Python 爬虫获得淘宝商品详情 数据【淘宝商品API】
大数据·开发语言·人工智能·爬虫·python·json·php
钢铁男儿2 小时前
Python 网络编程进阶:使用 SocketServer 模块构建 TCP 服务器与客户端
网络·python·tcp/ip
大模型真好玩3 小时前
深入浅出LangChain AI Agent智能体开发教程(十)—LangChain搭建数据分析智能助手
人工智能·python·mcp
七夜zippoe4 小时前
Python性能优化实战(三):给内存“减负“的实用指南
python·内存·优化
WSSWWWSSW9 小时前
Seaborn数据可视化实战:Seaborn数据可视化基础-从内置数据集到外部数据集的应用
python·信息可视化·数据分析·matplotlib·seaborn
Small___ming9 小时前
Matplotlib 可视化大师系列(七):专属篇 - 绘制误差线、等高线与更多特殊图表
python·信息可视化·matplotlib
荼蘼11 小时前
CUDA安装,pytorch库安装
人工智能·pytorch·python
杨荧12 小时前
基于Python的农作物病虫害防治网站 Python+Django+Vue.js
大数据·前端·vue.js·爬虫·python
骑驴看星星a13 小时前
数学建模--Topsis(Python)
开发语言·python·学习·数学建模