4

如何在 Java SE(不是 Java EE 或 Spring)中使用事务管理器(例如BitronixJBoss TSAtomikos)来支持以下用例:

假设我们有以下类:

public class Dao {

    public void updateDatabase(DB db) {
        connet to db
        run a sql
    }

}

然后我们从中创建一个 Java Runnable,如下所示:

public class MyRunnable extends Runnable {

    Dao dao;
    DB db;

    public MyRunnable(Dao dao, DB db) {
        this.dao=dao;
        this.db = db;
    }           

    public run() throws Exception {
        return dao.updateDatabase(db);
    }
}

现在在我们的服务层,我们有另一个类:

public class Service {

    public void updateDatabases() {

        BEGIN TRANSACTION;

        ExecutorService es = Executors.newFixedThreadPool(10);

        ExecutorCompletionService ecs = new ExecutorCompletionService(es);

        List<Future<T>> futures = new ArrayList<Future<T>>(n);

        Dao dao = new Dao();

        futures.add(ecs.submit(new MyRunnable(dao, new DB("db1")));
        futures.add(ecs.submit(new MyRunnable(dao, new DB("db2")));
        futures.add(ecs.submit(new MyRunnable(dao, new DB("db3")));

        for (int i = 0; i < n; ++i) {
            completionService.take().get();
        }

       END TRANSACTION;
    }

}

客户端可以是 Servlet 或任何其他多线程环境:

public MyServlet extend HttpServlet {

    protected void service(final HttpServletRequest request, final HttpServletResponse response) throws IOException {

        Service service = new Service();

        service.updateDatabases();

    }

}

BEGIN TRANSACTION 和 END TRANSACTION 部分的正确代码是什么?这甚至可行吗?如果不是,需要改变什么?要求是保持 updateDatabases() 方法并发(因为它将同时访问多个数据库)和事务性。

4

3 回答 3

3

似乎这可以使用Atomikos使用SubTxThread来完成

//first start a tx
TransactionManager tm = ...
tm.begin();

Waiter waiter = new Waiter();

//the code that calls the first EIS; defined by you
SubTxCode code1 = ...

//the associated thread
SubTxThread thread1 = new SubTxThread ( waiter , code1 );

//the code that calls the second EIS; defined by you
SubTxCode code2 = ...

//the associated thread
SubTxThread thread2 = new SubTxThread ( waiter , code2 );

//start each thread
thread1.start();

thread2.start();

//wait for completion of all calls
waiter.waitForAll();

//check result
if ( waiter.getAbortCount() == 0 ) {
    //no failures -> commit tx
    tm.commit();
} else {
    tm.rollback();
}
于 2011-03-15T19:38:42.110 回答
1

XA 规范要求所有 XA 调用都在同一个线程上下文中执行。详细说明其原因是因为可以在您的线程中创建任何事务分支之前调用提交。

如果您只是对如何在 JBoss TS 的 XA 事务中执行这三个调用感兴趣

首先确保您-ds.xml将数据源指定为<xa-datasource>

InitialContext ctx = new InitialContext(parms);
UserTransaction ut = (UserTransaction) ctx.lookup("java:comp/UserTransaction");

ut.begin();

//Some Transactional Code

ut.commit();

请记住,使用上面的代码,您将无法使用 ExecutorService 来并行化调用。

旁注:我对此了解不多,但 JTS/OTS 声称允许多个线程在事务中共享。我认为它通过传播类似于 ws-coordination/ws-transaction 的事务上下文来做到这一点,并且受 JBossTS 支持。可能是一条红鲱鱼,但如果你没有时间紧迫,它可能值得研究。

于 2011-03-13T15:56:18.697 回答
0

你呢

  1. BEGIN_TRANSATION:连接到您的服务中的所有 3 个数据库,
  2. 将 Connection 对象(而不是 db 对象)传递给 MyRunnable
  3. END_TRANSACTION:在您的服务中调用提交并关闭所有 3 个连接
于 2014-01-30T12:17:52.217 回答