java file transaction_JTA 五(XADisk java io Transaction 文件读写操作事务)

通常我们有时候会有一种需求,就是要对文件的操作,进行事务控制,在java提供的原生态的api中是没有办法实现这一点的,

而网上有open source的一个project提供了这种操作,就是XADisk,下面我只是做一个简单的Demo,其中的很多配置,以及api都没有详细的使用和列出来,有兴趣的朋友可以一直讨论.上代码:

public static void main(String[] args) throws Throwable {

try{

Jotm jotm=new Jotm(true,false);

TransactionManager transactionManager=jotm.getTransactionManager();

StandaloneFileSystemConfiguration configuration=new StandaloneFileSystemConfiguration("c:\\temp","Test-Instance");//创建configuration,

//一定要有的一个对象

XAFileSystem xaFileSystem=XAFileSystemProxy.bootNativeXAFileSystem(configuration);

transactionManager.begin();//事务开始

Transaction transaction=transactionManager.getTransaction();

try{

XASession xaSession=xaFileSystem.createSessionForXATransaction();//获得session

XAResource xaResource=xaSession.getXAResource(); //获得XAResource

File file=new File("c:\\temp\\a.txt");//文件 对象

file.setWritable(true);//设置权限

transaction.enlistResource(xaResource);//加入到事务

if(!xaSession.fileExists(file)){//判断并创建文件

xaSession.createFile(file, false);

}

XAFileOutputStream os=xaSession.createXAFileOutputStream(file,false);//创建文件流

os.write("HelloWorld".getBytes("UTF-8"));//写入数据

os.flush();

os.close();

transaction.commit();//提交事务

}catch(Throwable t){

t.printStackTrace();

transaction.rollback();

}finally{

jotm.stop();

}

}catch(Throwable e){

e.printStackTrace();

}finally{

System.exit(0);

}

}

以上就是文件操作的XA资源了,这个open source的功能,在一般的项目中并不多见,但是偶尔在一些比较让人郁闷的项目中可能遇到

至于说,要想让这个功能集成到spring,网上有人写了一个class的,可以去找下。这个class与BasicManagedDataSource类似,在获得XASession xaSession

对象的时候,先尝试将这个XASession xaSession相关的XAResource加入到当前事务,如果没有事务就异常(先开始事务,再获XASession)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值