您的位置:首页 > 编程语言 > Java开发

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

2016-04-14 00:00 591 查看
摘要: 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&n
3ff0
bsp;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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: