How to configure RetryAdvice and ExceptionTranslation for Deadlocks using NHibernate and Spring

时光总嘲笑我的痴心妄想 提交于 2019-11-30 21:22:22

After 1 and a half month of waiting for someone solving my problem i finally found time to elaborate the solution for this by myself. In fact it wasn't that difficult i thought it was. Maybe thats why i wasn't able to find any good example. So here we go: The following test will show the usage:

Configuration: (SessionFactory and TransactionManager etc. omitted for brevity)

  <!-- Retries the Tx after DeadlockExceptions -->
  <object name="ExceptionHandlingAdvice" type="Spring.Aspects.RetryAdvice, Spring.Aop">
    <property name="retryExpression" value="on exception name DeadlockLoserDataAccessException retry 3x delay 1s"/>
  </object>

  <!--A Transaction-Configuration for our DAO-MOCK-->  
  <object id="TxProxyConfigurationTemplate" abstract="true" type="Spring.Transaction.Interceptor.TransactionProxyFactoryObject, Spring.Data">
    <property name="PlatformTransactionManager" ref="HibernateTransactionManager"/>

    <property name="TransactionAttributes">
      <name-values>
        <add key="ThrowDeadLock*" value="PROPAGATION_REQUIRED"/>
      </name-values>
    </property>
  </object>

  <object id="MockDaoTxPFO" parent="TxProxyConfigurationTemplate">
    <property name="Target" ref="MockDao"/>
  </object>

  <!--The ProxyFactoryObject based on the DAO-Mock interface-->
  <object id="MockDao" type="Spring.Aop.Framework.ProxyFactoryObject, Spring.Aop" >
    <property name="proxyInterfaces" value="RetryAdvice.IDaoMock"/>
    <property name="target" ref="MockDaoImpl"/>
    <property name="interceptorNames">
      <list>
        <value>ExceptionHandlingAdvice</value>
      </list>
    </property>
  </object>

  <!--Mocked DAO Implementation -->
  <object id="MockDaoImpl" type="RetryAdvice.DaoMock, RetryAdvice">
    <constructor-arg name="maxExceptionCount" value="2" />
  </object>

Mocked Dao: This DAO will throw DeadLockLooserExceptions twice and then pass.

public interface IDaoMock
{
    void ThrowDeadLock();
    int MethodCallCount { get; }
}

[Repository]
public class DaoMock : IDaoMock
{
    private int maxExceptionCount;
    public int MethodCallCount { get; private set; }

    public DaoMock(int maxExceptionCount)
    {
        this.maxExceptionCount = maxExceptionCount;
    }

    public void ThrowDeadLock()
    {
        MethodCallCount++;
        if (MethodCallCount <= maxExceptionCount)
        {
            throw new DeadlockLoserDataAccessException("FAKE", new HibernateException("This is a fake Exception.", null));
        }
    }

The Test:

[Test]
public void RetryAdviceTest()
{
    IDaoMock mockDao = (IDaoMock)this.appContext.GetObject("MockDaoTxPFO");
    mockDao.ThrowDeadLock();
    Assert.That(mockDao.MethodCallCount, Is.EqualTo(3));
}

Any hints or remarks appreciated.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!