rabbitMQ处理异步发送确认模式下未确认消息

package com.wang;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmCallback;
import com.wang.conf.Config;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;

/**
 * @author username
 * @date 2021/11/7 21:06
 * @description:TODO
 * @since 11
 */
@Component
public class Producer {
    private static final String QUEUE_NAME="hello";
    public static void main(String[] args) throws IOException, InterruptedException {
        Channel channel = Config.getChannel();
        //处理并发的有序map集合,ConcurrentHashMap是无序的
        ConcurrentSkipListMap<Long,String> map = new ConcurrentSkipListMap<>();
        //开启发送确认模式
        channel.confirmSelect();
        ConfirmCallback confirmCallback =(deliveryTag, multiple )->{
            System.out.println(deliveryTag+"success received");
            //返回的消息有时候是批量确认的,批量确认需要判断!应该可以关闭批量确认的,但是不知道如何关闭
            if (multiple){
                ConcurrentNavigableMap<Long, String> confirmed = map.headMap(deliveryTag,true);
                confirmed.clear();
            }else {
                map.remove(deliveryTag);
            }
            if (map.size()==0){
                System.out.println("success send all message");
            }
        };
        ConfirmCallback confirmCallback1 = (deliveryTag, multiple)->{
            System.out.println(deliveryTag+"failed received");
        };
        channel.addConfirmListener(confirmCallback,confirmCallback1);
        long begin = System.currentTimeMillis();
        try {
            channel.queueDeclare(QUEUE_NAME,true,false,false,null);
            for (int i = 0; i < 100 ; i++) {
                String mes = "hello world"+i;
                channel.basicPublish("",QUEUE_NAME,null,mes.getBytes());
                //channel.getNextPublishSeqNo()获得的是下一个发布的序列号,当前序列号需要减一!
                map.put(channel.getNextPublishSeqNo()-1,mes);
            }
            long end = System.currentTimeMillis();
            System.out.println("time:"+(begin-end));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

        采用生产者创建监听器方式监听传来的异步确认消息

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值