Ehcache 事务管理源码探析

系统 2014 0

可能与大家关注点有不同,有考虑不周处,请大家指出...

Ehcache获取分布式事务支持可从net.sf.ehcache.transaction.manager. DefaultTransactionManagerLookup 类中知晓:

      
        private
      
      
        final
      
       JndiSelector defaultJndiSelector = 
      
        new
      
       JndiSelector("genericJNDI", "java:/TransactionManager");
      

private final Selector[] transactionManagerSelectors = new Selector[] {defaultJndiSelector,
new JndiSelector("Weblogic", "javax.transaction.TransactionManager"),
new FactorySelector("Bitronix", "bitronix.tm.TransactionManagerServices"),
new ClassSelector("Atomikos", "com.atomikos.icatch.jta.UserTransactionManager")};

默认获取JNDI名“java:/TransactionManager”。JBoss JTA事务。

现跟踪Ehcache PUT操作时是如何加入事务的。

当Ehcache配置成xa或者xa-strict时,内部使用net.sf.ehcache.transaction.xa.XATransactionStore存储逻辑,put操作如下:

      
        public
      
      
        boolean
      
       put(Element element) 
      
        throws
      
       CacheException {
      
LOG.debug("cache {} put {}", cache.getName(), element);
// this forces enlistment so the XA transaction timeout can be propagated to the XA resource
getOrCreateTransactionContext();

Element oldElement = getQuietFromUnderlyingStore(element.getObjectKey());
return internalPut( new StorePutCommand(oldElement, copyElementForWrite(element)));
}

红色部分是事务关键操作:初始化事务上下文

      
        private
      
       XATransactionContext getOrCreateTransactionContext() {
      
try {
EhcacheXAResourceImpl xaResource = getOrCreateXAResource();
XATransactionContext transactionContext = xaResource.getCurrentTransactionContext();

if (transactionContext == null ) {
transactionManagerLookup.register(xaResource);
LOG.debug("creating new XA context");
transactionContext = xaResource.createTransactionContext();
xaResource.addTwoPcExecutionListener( new UnregisterXAResource());
} else {
transactionContext = xaResource.getCurrentTransactionContext();
}

LOG.debug("using XA context {}", transactionContext);
return transactionContext;
} catch (SystemException e) {
throw new TransactionException("cannot get the current transaction", e);
} catch (RollbackException e) {
throw new TransactionException("transaction rolled back", e);
}
}
net.sf.ehcache.transaction.xa.EhcacheXAResourceImpl为Ehcache XAResource的实现。
研究一下XAResource都干了些啥。无非是该事务源相关属性及提交、回滚等操作吧。具体看一下实现代码:
关键属性:
        
          private
        
        
          final
        
         Ehcache cache;
        
private final Store underlyingStore;
private final TransactionIDFactory transactionIDFactory;
private final TransactionManager txnManager;
private final SoftLockFactory softLockFactory;
private final ConcurrentMap<Xid, XATransactionContext> xidToContextMap = new ConcurrentHashMap<Xid, XATransactionContext>();
private final XARequestProcessor processor;
private volatile Xid currentXid;
private volatile int transactionTimeout;
private final List<XAExecutionListener> listeners = new ArrayList<XAExecutionListener>();
private final ElementValueComparator comparator;
......
关键方法:
        
          public
        
        
          void
        
         commit(Xid xid, 
        
          boolean
        
         onePhase)
        
public void rollback(Xid xid) throws XAException
/**
* Add a listener which will be called back according to the 2PC lifecycle
*
@param listener the XAExecutionListener
*/
void addTwoPcExecutionListener(XAExecutionListener listener);
/**
* Obtain the already associated {
@link XATransactionContext} with the current Transaction,
* or create a new one should none be there yet.
*
@return The associated Transaction associated { @link XATransactionContext}
*/
XATransactionContext createTransactionContext() throws SystemException, RollbackException;
前两个为XAResource接口抽象方法,完成事务的基本操作,在JTA事务提交或是回滚时会被调用;后面是Ehcache抽象出来的接口方法。
接着关心这里的rollback()方法都做了啥。关键代码如下:
         int rc = prepareInternal(xid);
      

  if (rc == XA_RDONLY) {
   return;
   }

        
          public
        
        
          int
        
         prepareInternal(Xid xid) 
        
          throws
        
         XAException {
        
fireBeforePrepare();

XATransactionContext twopcTransactionContext = xidToContextMap.get(xid);
if (twopcTransactionContext == null ) {
throw new EhcacheXAException("transaction never started: " + xid, XAException.XAER_NOTA);
}

XidTransactionID xidTransactionID = transactionIDFactory.createXidTransactionID(xid);

List<Command> commands = twopcTransactionContext.getCommands();
List<Command> preparedCommands = new LinkedList<Command>();

boolean prepareUpdated = false ;
LOG.debug("preparing {} command(s) for [{}]", commands.size(), xid);
for (Command command : commands) {
try {
prepareUpdated |= command.prepare(underlyingStore, softLockFactory, xidTransactionID, comparator);
preparedCommands.add(0, command);
} catch (OptimisticLockFailureException ie) {
for (Command preparedCommand : preparedCommands) {
preparedCommand.rollback(underlyingStore);
}
preparedCommands.clear();
throw new EhcacheXAException(command + " failed because value changed between execution and 2PC",
XAException.XA_RBINTEGRITY, ie);
}
}

xidToContextMap.remove(xid);

if (!prepareUpdated) {
rollbackInternal(xid);
}

LOG.debug("prepared xid [{}] read only? {}", xid, !prepareUpdated);
return prepareUpdated ? XA_OK : XA_RDONLY;
}
可以看到进行了底部存储逻辑的回滚处理。
实例化好XAResource后回到初始化事务上下文方法getOrCreateTransactionContext中,可以知道通过该XAResource直接取得XATransactionContext。并且给XAResource注册了两个监听器UnregisterXAResource和CleanupXAResource(在事务提交或是混回滚时启动)。
至此事务的初始化工作完成。
 
理一下put过程。外部调用 XATransactionStore 的put方法,向当前XID的XATransactionContext中添加addCommand(封装了针对指定cache具体的提交与回滚操作),接着控制权到事务管理中,事务管理器管理 EhcacheXAResourceImpl 对象,提交与回滚操作通过取得XATransactionContext中的Commands对象并执行来完成。

欢迎大家批评指正!

 
 

Ehcache 事务管理源码探析


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论