RabbitMQ学习笔记6-事务机制
事务机制
在使用RabbitMQ的时候,我们可以通过消息持久化操作来解决因为服务器的异常奔溃导致的消息丢失,除此之外我们还会遇到一个问题,当消息的发布者在将消息发送出去之后,消息到底有没有正确到达broker代理服务器呢?如果不进行特殊配置的话,默认情况下发布操作是不会返回任何信息给生产者的,也就是默认情况下我们的生产者是不知道消息有没有正确到达broker的,如果在消息到达broker之前已经丢失的话,持久化操作也解决不了这个问题,因为消息根本就没到达代理服务器,你怎么进行持久化,那么这个问题该怎么解决呢?
RabbitMQ为我们提供了两种方式:
1) 通过AMQP事务机制实现,这也是AMQP协议层面提供的解决方案;
2) 通过将channel设置成confirm模式来实现;
AMQP事务机制
描述
RabbitMQ中与事务机制有关的方法有三个:txSelect(), txCommit()以及txRollback(), txSelect用于将当前channel设置成transaction模式,txCommit用于提交事务,txRollback用于回滚事务,在通过txSelect开启事务之后,我们便可以发布消息给broker代理服务器了,如果txCommit提交成功了,则消息一定到达了broker了,如果在txCommit执行之前broker异常崩溃或者由于其他原因抛出异常,这个时候我们便可以捕获异常通过txRollback回滚事务了。这种模式比较耗时,降低rabbitmq的吞吐量。
代码
生产者
package com.lin.rabbit.tx; import java.io.IOException; import java.util.concurrent.TimeoutException; import com.lin.rabbit.utils.ConnectionUtils; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; public class TxProvider { public static void main(String[] args) throws IOException, TimeoutException { //获取连接 Connection con = ConnectionUtils.getConnection(); //创建通道 Channel channel = con.createChannel(); //声明队列 channel.queueDeclare(TxConstant.TX_QUEUE_NAME, false, false, false, null); //发送第一条消息 String msg = "你好 第一条消息"; //事务处理 try { channel.txSelect(); channel.basicPublish("", TxConstant.TX_QUEUE_NAME, null, msg.getBytes("UTF-8")); channel.txCommit(); System.out.println("send msg:"+msg); } catch (Exception e) { e.printStackTrace(); channel.txRollback(); } //发送第二条消息 msg = "你好 第二条消息"; //事务处理 try { channel.txSelect(); channel.basicPublish("", TxConstant.TX_QUEUE_NAME, null, msg.getBytes("UTF-8")); //抛出异常 float f =1/0; channel.txCommit(); System.out.println("send msg:"+msg); } catch (Exception e) { e.printStackTrace(); channel.txRollback(); } //关闭通道和连接 channel.close(); con.close(); } }
消费者
package com.lin.rabbit.tx; import java.io.IOException; import java.util.concurrent.TimeoutException; import com.lin.rabbit.utils.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 TxConsumer { public static void main(String[] args) throws IOException, TimeoutException { //获取连接 Connection con = ConnectionUtils.getConnection(); //创建通道 Channel channel = con.createChannel(); //声明队列 channel.queueDeclare(TxConstant.TX_QUEUE_NAME, false, false, false, null); //消息获取 DefaultConsumer defaultConsumer = 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("receiver msg:"+msg); } }; channel.basicConsume(TxConstant.TX_QUEUE_NAME, true, defaultConsumer); } }
辅助类
package com.lin.rabbit.tx; public class TxConstant { public static String TX_QUEUE_NAME = "tx-queue"; }
演示效果
1) 启动消费者
2) 启动生产者
3) 查看消费者
confirm事务机制
描述
生产者将信道设置成confirm模式,一旦信道进入confirm模式,所有在该信道上面发布的消息都会被指派一个唯一的ID(从1开始),一旦消息被投递到所有匹配的队列之后,broker就会发送一个确认给生产者(包含消息的唯一ID),这就使得生产者知道消息已经正确到达目的队列了,如果消息和队列是可持久化的,那么确认消息会将消息写入磁盘之后发出,broker回传给生产者的确认消息中deliver-tag域包含了确认消息的序列号,此外broker也可以设置basic.ack的multiple域,表示到这个序列号之前的所有消息都已经得到了处理。confirm模式最大的好处在于他是异步的,一旦发布一条消息,生产者应用程序就可以在等信道返回确认的同时继续发送下一条消息,当消息最终得到确认之后,生产者应用便可以通过回调方法来处理该确认消息,如果RabbitMQ因为自身内部错误导致消息丢失,就会发送一条nack消息,生产者应用程序同样可以在回调方法中处理该nack消息。在channel 被设置成 confirm 模式之后,所有被 publish 的后续消息都将被 confirm(即 ack) 或者被nack一次。但是没有对消息被 confirm 的快慢做任何保证,并且同一条消息不会既被 confirm又被nack 。
Confirm的三种实现方式:
方式一:channel.waitForConfirms()普通发送方确认模式;
方式二:channel.waitForConfirmsOrDie()批量确认模式;
方式三:channel.addConfirmListener()异步监听发送方确认模式;
普通模式
生产者
package com.lin.rabbit.confirm; import java.io.IOException; import java.util.concurrent.TimeoutException; import com.lin.rabbit.utils.ConnectionUtils; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; public class ConfirmSimpleProvider { public static void main(String[] args) throws IOException, TimeoutException, InterruptedException { //获取连接 Connection con = ConnectionUtils.getConnection(); //创建通道 Channel channel = con.createChannel(); //声明队列 channel.queueDeclare(ConfirmConstant.CONFIRM_SIMPLE_QUEUE_NAME, false, false, false, null); //发送第一条消息 String msg = "this is confirm simple model"; // confirm模式:设置为confirm模式,注意如果队列之前设置成事务模式,那么不可以在设置为confirm模式 channel.confirmSelect(); channel.basicPublish("", ConfirmConstant.CONFIRM_SIMPLE_QUEUE_NAME, null, msg.getBytes("UTF-8")); if(channel.waitForConfirms()) { System.out.println("send message: \""+msg+"\" is success!"); }else { System.out.println("send message: \""+msg+"\" is fail!"); } //关闭通道和连接 channel.close(); con.close(); } }
消费者
package com.lin.rabbit.confirm; import java.io.IOException; import java.util.concurrent.TimeoutException; import com.lin.rabbit.utils.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 ConfirmSimpleConsumer { public static void main(String[] args) throws IOException, TimeoutException { //获取连接 Connection con = ConnectionUtils.getConnection(); //创建通道 Channel channel = con.createChannel(); //声明队列 channel.queueDeclare(ConfirmConstant.CONFIRM_SIMPLE_QUEUE_NAME, false, false, false, null); //消息获取 DefaultConsumer defaultConsumer = 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("receiver msg:"+msg); } }; channel.basicConsume(ConfirmConstant.CONFIRM_SIMPLE_QUEUE_NAME, true, defaultConsumer); } }
辅助类
package com.lin.rabbit.confirm; public class ConfirmConstant { public static String CONFIRM_SIMPLE_QUEUE_NAME = "confirm-simple-queue"; }
批量模式
生产者
package com.lin.rabbit.confirm; import java.io.IOException; import java.util.concurrent.TimeoutException; import com.lin.rabbit.utils.ConnectionUtils; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; public class ConfirmBatchProvider { public static void main(String[] args) throws IOException, TimeoutException, InterruptedException { //获取连接 Connection con = ConnectionUtils.getConnection(); //创建通道 Channel channel = con.createChannel(); //声明队列 channel.queueDeclare(ConfirmConstant.CONFIRM_BATCH_QUEUE_NAME, false, false, false, null); //发送第一条消息 String msg = "this is confirm batch model"; // confirm模式:设置为confirm模式,注意如果队列之前设置成事务模式,那么不可以在设置为confirm模式 channel.confirmSelect(); for(int i=0;i<10;i++) channel.basicPublish("", ConfirmConstant.CONFIRM_BATCH_QUEUE_NAME, null, msg.getBytes("UTF-8")); if(channel.waitForConfirms()) { System.out.println("send message: \""+msg+"\" is success!"); }else { System.out.println("send message: \""+msg+"\" is fail!"); } //关闭通道和连接 channel.close(); con.close(); } }
消费者
package com.lin.rabbit.confirm; import java.io.IOException; import java.util.concurrent.TimeoutException; import com.lin.rabbit.utils.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 ConfirmBatchConsumer { public static void main(String[] args) throws IOException, TimeoutException { //获取连接 Connection con = ConnectionUtils.getConnection(); //创建通道 Channel channel = con.createChannel(); //声明队列 channel.queueDeclare(ConfirmConstant.CONFIRM_BATCH_QUEUE_NAME, false, false, false, null); //消息获取 DefaultConsumer defaultConsumer = 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("receiver msg:"+msg); } }; channel.basicConsume(ConfirmConstant.CONFIRM_BATCH_QUEUE_NAME, true, defaultConsumer); } }
辅助类
package com.lin.rabbit.confirm; public class ConfirmConstant { public static String CONFIRM_SIMPLE_QUEUE_NAME = "confirm-simple-queue"; public static String CONFIRM_BATCH_QUEUE_NAME = "confirm-batch-queue"; }
异步模式
异步confirm模式的编程实现最复杂,Channel对象提供的ConfirmListener()回调方法只包含deliveryTag(当前Chanel发出的消息序号),我们需要自己为每一个Channel维护一个unconfirm的消息序号集合,每publish一条数据,集合中元素加1,每回调一次handleAck方法,unconfirm集合删掉相应的一条(multiple=false)或多条(multiple=true)记录。从程序运行效率上看,这个unconfirm集合最好采用有序集合SortedSet存储结构。
生产者
package com.lin.rabbit.confirm; import java.io.IOException; import java.util.Collections; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.TimeoutException; import com.lin.rabbit.utils.ConnectionUtils; import com.rabbitmq.client.Channel; import com.rabbitmq.client.ConfirmListener; import com.rabbitmq.client.Connection; public class ConfirmSyncProvider { public static void main(String[] args) throws IOException, TimeoutException, InterruptedException { //获取连接 Connection con = ConnectionUtils.getConnection(); //创建通道 Channel channel = con.createChannel(); //声明队列 channel.queueDeclare(ConfirmConstant.CONFIRM_SYNC_QUEUE_NAME, false, false, false, null); //confirm模式:设置为confirm模式,注意如果队列之前设置成事务模式,那么不可以在设置为confirm模式 channel.confirmSelect(); //unconfirm的集合 final SortedSet<Long> confirmSet = Collections.synchronizedSortedSet(new TreeSet<Long>()); //设置回调监听 channel.addConfirmListener(new ConfirmListener() { //成功消息回调 public void handleAck(long deliveryTag, boolean multiple) throws IOException { System.out.println("Ack, SeqNo: " + deliveryTag + ", multiple: " + multiple); if (multiple) { confirmSet.headSet(deliveryTag + 1).clear(); } else { confirmSet.remove(deliveryTag); } } //失败消息回调 public void handleNack(long deliveryTag, boolean multiple) throws IOException { System.out.println("Nack, SeqNo: " + deliveryTag + ", multiple: " + multiple); if (multiple) { confirmSet.headSet(deliveryTag + 1).clear(); } else { confirmSet.remove(deliveryTag); } } }); //发送消息 String msg = "this is confirm sync model.num="; int num = 0; while(true) { long nextSeqNo = channel.getNextPublishSeqNo(); channel.basicPublish("", ConfirmConstant.CONFIRM_SYNC_QUEUE_NAME, null, (msg+num).getBytes("UTF-8")); confirmSet.add(nextSeqNo); num++; if(num>50) break; } //关闭通道和连接 while(true) { if(confirmSet.size()==0) { break; } Thread.sleep(500); } channel.close(); con.close(); } }
消费者
package com.lin.rabbit.confirm; import java.io.IOException; import java.util.concurrent.TimeoutException; import com.lin.rabbit.utils.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 ConfirmSyncConsumer { public static void main(String[] args) throws IOException, TimeoutException { //获取连接 Connection con = ConnectionUtils.getConnection(); //创建通道 Channel channel = con.createChannel(); //声明队列 channel.queueDeclare(ConfirmConstant.CONFIRM_SYNC_QUEUE_NAME, false, false, false, null); //消息获取 DefaultConsumer defaultConsumer = 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("receiver msg:"+msg); } }; channel.basicConsume(ConfirmConstant.CONFIRM_SYNC_QUEUE_NAME, true, defaultConsumer); } }
辅助类
package com.lin.rabbit.confirm; public class ConfirmConstant { public static String CONFIRM_SIMPLE_QUEUE_NAME = "confirm-simple-queue"; public static String CONFIRM_BATCH_QUEUE_NAME = "confirm-batch-queue"; public static String CONFIRM_SYNC_QUEUE_NAME = "confirm-sync-queue"; }
演示效果
1) 启动消费者
2) 启动生产者
3) 查看消费者
- MySQL学习笔记之四:并发控制和事务机制
- MySql学习笔记——锁与事务机制
- 数据库:深入浅出mysql学习笔记【超级详细(七)】--mysql的事务机制
- MySQL学习笔记之四:并发控制和事务机制
- spring事务传播机制和隔离级别学习笔记
- 学习RabbitMQ(三):AMQP事务机制
- rabbitmq学习笔记-----分发机制
- Java学习笔记——反射机制
- CSS学习笔记:三种定位机制之一标准文档流
- Java的反射机制学习笔记
- Silverlight学习笔记一(理解一下机制,使用一下布局,实现一个简单的用户登录)
- Java学习笔记之垃圾回收机制
- Xcode SCM系统 使用Git存储库机制之 学习笔记
- Redis学习笔记6--Redis事务
- Android应用开发学习笔记之多线程与Handler消息处理机制
- Struts2_学习笔记(一)--------学习工具下载、HelloWorld、运行机制
- java事务学习笔记总结
- RabbitMQ之消息确认机制(事务+Confirm) - 朱小厮的博客 - CSDN博客
- jvm内存JVM学习笔记-引用(Reference)机制
- IOS学习笔记—苹果推送机制APNs