RabbitMq08——Transaction(事务)

之前我们确定一个消息是否发送成功是从消费者是否接收到来判断的,但是在实际应用中,消费者和生产者往往是分开部署的,我们也不可能每发送一条消息就去消费者那里确认一下,所有我们需要一个机制来确认消息发送后是否成功到达了消息队列,下面来介绍几种在生产者端来确认消息发送状态的方法。

事务模式类似与数据库中所讲的事务。也是分为三个步骤:开启事务,提交事务,回滚事务。

生产者

package com.mmr.rabbitmq.tx;

import com.mmr.rabbitmq.util.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

public class Send {
	
	private static final String QUEUE_NAME="QUEUE_TX";//定义队列名

	public static void main(String[] args) throws Exception
	{
		Connection connection = ConnectionUtils.getConnection();
		
		Channel channel = connection.createChannel();//获取一个信道
		
		channel.queueDeclare(QUEUE_NAME, false, false, false, null);
		
		try
		{
			channel.txSelect(); //开启事务
			String msg="Hello Simple QUEUE !";
			channel.basicPublish("", QUEUE_NAME, null, msg.getBytes());
			
//			int result = 1 / 0; //假设向队列发送消息时出错
			
			channel.txCommit(); //提交事务
			System.out.println("---------send ms :"+msg);
		} catch (Exception e)
		{
			channel.txRollback(); //回滚事务
			System.out.println("发送失败,事务回滚!!!");
		}
		
		channel.close();
		connection.close();
	}

}

消费者

package com.mmr.rabbitmq.tx;

import java.io.IOException;

import com.mmr.rabbitmq.util.ConnectionUtils;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

public class Recv {
	
	private static final String QUEUE_NAME="QUEUE_TX";	
	
	public static void main(String[] args) throws Exception {
		
		Connection connection = ConnectionUtils.getConnection();
		Channel channel = connection.createChannel();
		
		channel.queueDeclare(QUEUE_NAME, false, false, false, null);
		
		//定义一个默认的消费者
		DefaultConsumer consumer = new DefaultConsumer(channel){

			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
					throws IOException {
				String msg = new String(body, "utf-8");
				System.out.println("Rev--->" + msg);
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		
		channel.basicConsume(QUEUE_NAME, true, consumer);
		
	}

}

长按关注公众号“魔性JAVA”,会不定时免费推送JAVA相关的学习资料和知识

猜你喜欢

转载自blog.csdn.net/yangsheng0111/article/details/81024211