消息中间件--RabbitMQ学习(十一)---高级特性之Confirm确认消息

Confirm消息确认机制

  • 消息的确认,是指生产者投递消息后,如果 Broker收到消息,则会给我们生产者一个应答
  • 生产者进行接收应答,用来确定这条消息是否正常的发送到 Broker,这种方式也是消息的可靠性投递的核心保障

确认消息流程图
在这里插入图片描述

代码实现:

消费端代码

public class Consumer {

    public static void main(String[] args) throws Exception{
        //1 创建一个connectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.0.159");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        //2通过连接工场创建连接
        Connection connection = connectionFactory.newConnection();
        //3通过connection创建channel
        Channel channel = connection.createChannel();
        String exchangeName = "test_confirm_exchange";
        String routingKey = "confirm.#";

        channel.exchangeDeclare(exchangeName,"topic",true);
        channel.queueDeclare("test_confirm_queue",true,false,false,null);
        channel.queueBind("test_confirm_queue",exchangeName,routingKey);

        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume("test_confirm_queue",true,consumer);
        while (true){
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.out.println("消费者:" + msg);
        }
    }
}

生产端代码

public class Producter {
    public static void main(String[] args) throws Exception{
        //1 创建一个connectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.0.159");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        //2通过连接工场创建连接
        Connection connection = connectionFactory.newConnection();
        //3通过connection创建channel
        Channel channel = connection.createChannel();
        //开启消息的确认模式
        channel.confirmSelect();
        String exchangeName = "test_confirm_exchange";
        String routingKey = "confirm.save";

        //发送消息
        String msg = "hello";
        channel.basicPublish(exchangeName,routingKey,null,msg.getBytes());

        //添加确认监听
        channel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleAck(long l, boolean b) throws IOException {
                System.out.println("**success**");
            }

            @Override
            public void handleNack(long l, boolean b) throws IOException {
                System.err.println("**error**");
            }
        });

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值