请波总 @JFinal 看看是否有问题,我用ab测试1000访问,10并发,感觉没有看出有问题。
使用Tx.Class的唯一问题的,如果业务想回滚,而不是Action执行出错的话,没办法回滚,另外就是违反了尽可能晚的声明事务,尽可能早的提交事务的原则,因此我查看了Tx的代码,把相关代码提取出来了,使用方法如下:
TxKit txKit = new TxKit(); txKit.Begin(); txKit.Rollback(); txKit.Commit();
TxKit的代码如下:
public class TxKit { private Boolean originAutoCommit = null; private Config config = null; private Connection conn = null; public boolean Begin() { config = DbKit.getConfig(); conn = config.getThreadLocalConnection(); if (conn != null) { // Nested transaction support try { if (!conn.isClosed() && conn.getTransactionIsolation() < config.getTransactionLevel()) conn.setTransactionIsolation(config.getTransactionLevel()); return true; } catch (SQLException e) { throw new ActiveRecordException(e); } } try { conn = config.getConnection(); originAutoCommit = conn.getAutoCommit(); config.setThreadLocalConnection(conn); conn.setTransactionIsolation(config.getTransactionLevel()); // conn.setTransactionIsolation(transactionLevel); conn.setAutoCommit(false); return true; } catch (Exception e) { if (conn != null) try {conn.rollback();} catch (Exception e1) {LogKit.error(e.getMessage(), e);} try { if (conn != null) { if (originAutoCommit != null) conn.setAutoCommit(originAutoCommit); conn.close(); } return false; } catch (Throwable t) { // can not throw exception here, otherwise the more important exception in previous catch block can not be thrown LogKit.error(t.getMessage(), t); return false; } } } public boolean Commit() { try { conn.commit(); if (conn != null) { if (originAutoCommit != null) conn.setAutoCommit(originAutoCommit); conn.close(); } return true; } catch (Exception e) { try { if (conn != null) { if (originAutoCommit != null) conn.setAutoCommit(originAutoCommit); conn.close(); conn = null; } return false; } catch (Exception e2) { return false; } } finally { config.removeThreadLocalConnection(); } } public boolean Rollback() { try { conn.rollback(); if (conn != null) { if (originAutoCommit != null) conn.setAutoCommit(originAutoCommit); conn.close(); } return true; } catch (Exception e) { try { if (conn != null) { if (originAutoCommit != null) conn.setAutoCommit(originAutoCommit); conn.close(); } return false; } catch (Exception e2) { return false; } } finally { config.removeThreadLocalConnection(); } } }