07. Mecanismo de confirmación de éxito del mensaje RabbitMQ

07. Mecanismo de confirmación de éxito del mensaje RabbitMQ

  • En escenarios reales, se debe garantizar que los mensajes enviados por algunos productores se envíen correctamente a la cola de mensajes, entonces, ¿cómo garantizar una entrega exitosa?

    • mecanismo de transacción
    • Mecanismo de confirmación de liberación

1. Mecanismo de transacción

  • Una forma de asegurar la entrega exitosa de los mensajes proporcionados por el protocolo AMQP, habilitando el modo transaccional a través del canal

  • Y use los tres métodos del canal para enviar mensajes de manera transaccional.Si el envío falla, la transacción se revierte mediante el manejo de excepciones para garantizar la entrega exitosa del mensaje.

    • channel.txSelect(): transacción abierta
    • channel.txCommit() : Confirma la transacción
    • channel.txRollback() : deshacer la transacción
  • Spring ha encapsulado los tres métodos anteriores, por lo que solo podemos usar la demostración del código original

2. Código del productor

package trascation;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import util.ConnectionUtil;

/**
 * @author WeiHong
 * @date 2021 -  09 - 15 19:59
 */
public class Sender {
    
    
    public static void main(String[] args) throws Exception {
    
    
        //1.获取连接
        Connection connection = ConnectionUtil.getConnection();
        //2.在连接中创建信道
        Channel channel = connection.createChannel();
        //3.声明路由
        channel.exchangeDeclare("trascation_exchange_topic","topic");
        //4.发送消息
        channel.txSelect();  //开启事务
        try {
    
    
            channel.basicPublish("trascation_exchange_topic","user.weihong",null,"商品1-降价".getBytes());
            System.out.println(3/0);//模拟异常
            channel.basicPublish("trascation_exchange_topic","user.libai",null,"商品2-降价".getBytes());
            channel.basicPublish("trascation_exchange_topic","users123.wangwu",null,"商品3-降价".getBytes());
            System.out.println("生产者已发送!");
            channel.txCommit();//事务提交
        }catch(Exception e){
    
    
            System.out.println("由于系统异常,消息全部撤回!");
            channel.txRollback();//事务回滚
            e.printStackTrace();
        }finally {
    
    
            channel.close();
            connection.close();
        }

    }
}

3. Código del Consumidor

package trascation;

import com.rabbitmq.client.*;
import util.ConnectionUtil;

import java.io.IOException;

/**
 * @author WeiHong
 * @date 2021 -  09 - 15 20:10
 */
public class Recer1 {
    
    
    public static void main(String[] args) throws Exception {
    
    
        //1.创建连接
        Connection connection = ConnectionUtil.getConnection();
        //2.在连接中创建信道
        Channel channel = connection.createChannel();
        //3.声明队列
        channel.queueDeclare("trscation_queue_topic1",false,false,false,null);
        //4.绑定路由
        channel.queueBind("trscation_queue_topic1","trascation_exchange_topic","user.#");
        //5.定义内部类接收消息
        DefaultConsumer consumer = new DefaultConsumer(channel){
    
    
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
    
    
                String msg = new String(body);
                System.out.println("消费者1="+msg);
            }
        };
        channel.basicConsume("trscation_queue_topic1",true,consumer);


    }
}

4. Resultados experimentales

imagen

Supongo que te gusta

Origin blog.csdn.net/qq_41239465/article/details/123676629
Recomendado
Clasificación