设为首页 收藏本站
查看: 871|回复: 0

[经验分享] Ehcache 事务管理源码探析

[复制链接]

尚未签到

发表于 2017-2-19 07:57:01 | 显示全部楼层 |阅读模式
  可能与大家关注点有不同,有考虑不周处,请大家指出...
  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事务。如果需要其他类型的事务管理获取方式,
  通过配置TransactionManagerLookup来替代默认的。
  配置如下:


  <transactionManagerLookup
  class= "com.mycompany.transaction.manager.MyTransactionManagerLookupClass"
  properties="" propertySeparator=":"/>
  另外当使用默认的事务管理查找类,但是不同的JNDI查找名称,可以配置:


  <transactionManagerLookup
class="net.sf.ehcache.transaction.manager.DefaultTransactionManagerLookup"
properties="jndiName=java:appserver/TransactionManager" propertySeparator=";"/>
  现跟踪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)));
    }
  红色部分是事务关键操作:初始化事务上下文。事务上下文维护着该事务的所有cache操作、remove操作的keys、put操作的keys和underlyingStore。



    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);
        }
    }

构建事务上下文的操作:




public XATransactionContext createTransactionContext() throws SystemException, RollbackException {
        XATransactionContext ctx = getCurrentTransactionContext();
        if (ctx != null) {
            return ctx;
        }
        Transaction transaction = txnManager.getTransaction();
        LOG.debug("enlisting {} in {}", this, transaction);
        transaction.enlistResource(this);//关键操作:注册当前XAResource到事务中
        // currentXid is set by a call to start() which itself is called by transaction.enlistResource(this)
        if (currentXid == null) {
            throw new CacheException("enlistment of XAResource of cache named '" + getCacheName() +
                    "' did not end up calling XAResource.start()");
        }
        ctx = xidToContextMap.get(currentXid);
        if (ctx == null) {
            LOG.debug("creating new context for XID [{}]", currentXid);
            ctx = new XATransactionContext(underlyingStore);
            xidToContextMap.put(currentXid, ctx);
        }
        return ctx;
    }

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对象并执行来完成。  欢迎大家批评指正!

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-344017-1-1.html 上篇帖子: Web服务器与应用服务器 下篇帖子: JSF 学习笔记
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表