Home > Software design >  Execute 2 mthods in a songle transaction with separate Retry logic
Execute 2 mthods in a songle transaction with separate Retry logic

Time:10-05

Below is my requirement

begin trans
insertData();
updateData();
end trans

Also lets say insertDta method throws some error then I need to retry 5 times .Same with updateData().I should not retry both the methods at the same time i.e if i retry m2() 5 times them m1() should not be retried. Is below the correct way to do it? I call m3() from another class . My concern is that interceptors are added in correct and deterministic order.

@Repository
DaoA
{
    void insertData();
}

@Repository
DaoB
{
    void updateData();
}

Below is my Service class .

@Service
ServiceA 
{
    
    @Retryable(  maxAttempts = 5)
     public void m1 ()
     {
         
         daoA.insertData();
         
     }
    
    
     @Retryable(  maxAttempts = 5)
     public void m2 ()
     {
          daoB.updateData();
     }
    
    

    @Transactional
     public void m3 ()
     {
         
    
          m1();
          m2();
     }
    

CodePudding user response:

m3() needs to be in a different bean - calling m1() and m2() directly within the class bypasses the proxy and they won't be retried.

In any case, the transaction should be within the retry logic, not the other way around; you need to start a new transaction for each attempt.

CodePudding user response:

If I got your requirement right, this should work for you.

@Service
ServiceA {
    
    public void m1 () {
         daoA.insertData();
     }
    
    public void m2 () {
          daoB.updateData();
    }

    @Transactional
    @Retryable(value = {Exception.class}, maxAttempts = 5)
    public void m3 () {
          m1();
          m2();
    }
}

This will make sure the total number of retries is maxAttempts = 5.

  • Related