【发布时间】:2014-06-28 01:27:22
【问题描述】:
我正试图围绕 Java Transactions API (JTA) 及其实现之一 Bitronix 下的 value。但是随着我对文档的深入挖掘,我不禁想到了以下简单的示例:
public interface Transactional {
public void commit(Object);
public void rollback();
}
public class TransactionalFileWriter extends FileWriter implements Transactional {
@Override
public void commit(Object obj) {
String str = (String)obj;
// Write the String to a file.
write(str);
}
@Override
public void rollback() {
// Obtain a handler to the File we are writing to, and delete the file.
// This returns the file system to the state it was in before we created a file and started writing to it.
File f = getFile();
// This is just pseudo-code for the sake of this example.
File.delete(f);
}
}
// Some method in a class somewhere...
public void doSomething(File someFile) {
TransactionalFileWriter txFileWriter = getTxFW(someFile);
try {
txFileWriter.commit("Create the file and write this message to it.");
} catch(Throwable t) {
txFileWriter.rollback();
}
}
不要太拘泥于上面的实际代码。这个想法很简单:一个事务文件编写器,它创建一个文件并写入它。 rollback() 方法删除文件,从而使文件系统恢复到 commit(Object) 之前的相同状态。
我在这里遗漏了什么吗?这就是 JTA 提供的全部内容吗?还是我上面的简单示例没有代表交易性的一组完全不同的维度/方面?我猜是后者,但尚未在 JTA 文档中看到任何具体内容。如果我遗漏了什么,那是什么,有人可以告诉我具体示例吗?我可以看到事务性是 JDBC 的一个重要组成部分,但希望获得一个 JTA 与数据库以外的东西一起使用的示例。
【问题讨论】:
-
你有没有想过分布式事务&
Transactional.getStatus(),begin(),setTransactionTimeout()。除了数据库,你有没有想过 JMS? JTA 提供的不仅仅是那个简单的界面。你也想过“当前活跃的交易”并加入吗? -
谢谢@AndreiI (+1) - 你能解释一下“当前活跃交易”是什么,“加入”它意味着什么?
-
关于“当前活动事务”:有时您需要一种机制来决定是否要加入事务。在 JTA 中,您(据我所知)有一个附加到线程(可以暂停)的当前活动事务,并且在您的代码中,您可以动态决定您的
EntityManager(JPA 规范)加入它,以便提交您在其他一些请求中所做的更改。 -
我想知道如果不是为了防止因赏金而关闭,这个问题需要多长时间才能关闭,因为过于宽泛或基于意见。
-
@OlegEstekhin 可能需要 7 天(如果有的话):) 因为赏金问题无法关闭。