赞
踩
RabbitMQ中与事务机制有关的方法有三个:txSelect(), txCommit()以及txRollback(), txSelect用于将当前channel设置成transaction模式,txCommit用于提交事务,txRollback用于回滚事务,在通过txSelect开启事务之后,我们便可以发布消息给broker代理服务器了,如果txCommit提交成功了,则消息一定到达了broker了,如果在txCommit执行之前broker异常崩溃或者由于其他原因抛出异常,这个时候我们便可以捕获异常通过txRollback回滚事务了。
- public class P1 {
-
- private static final String QUEUE_NAME = "test_tx";
- public static void main(String[] args) throws IOException, TimeoutException {
- Connection connection = ConnectionUtils.getConnection();
- Channel channel = connection.createChannel();
-
- channel.queueDeclare(QUEUE_NAME,false,false,true,null);
- SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
- Date date = new Date(System.currentTimeMillis());
- String message = simpleDateFormat.format(date);
-
- try {
- channel.txSelect();//开始事务
- channel.basicPublish("",QUEUE_NAME,null,message.getBytes());
- channel.txCommit();//提交事务
- }catch (Exception e){
- channel.txRollback();//回滚事务
- System.out.println("send message txRollback");
- }
- channel.close();
- connection.close();
-
-
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。