Friday, 31 May 2013

Lessons Learned: Avoiding Distributed Transaction Management

In one particular project we were using an Oracle 11g Database and XA Datasources to persist transactions to multiple database environments. Whilst in theory this is fine, it wasn't really needed and by reverting to a more modular separate transaction management (as illustrated bellow) huge gains in performance were obtained.

Therefore I would strongly recommend alternatives to global transactions on XA Datasources to multiple databases. Unless it is really needed


Example Seperate Datasource Configurations


Multiple Transaction Manager IOC Configurations

<beans xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <bean id="firstTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="firstEntityManagerFactory"/>
        <qualifier value="first"/>
    </bean>

    <bean id="secondTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="secondEntityManagerFactory"/>
        <qualifier value="second"/>
    </bean>

    <tx:annotation-driven />
</beans>

Custom transactional annotations for the transaction managers

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional("first")
public @interface FirstTransactional {
}

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional("second")
public @interface SecondTransactional {
}

Custom transactional annotations embedded within a service

@Service("exampleService")
public class ExampleServiceImpl implements ExampleService{

    @FirstTransactional
    public boolean saveToFirstDatabase(ReceivedEvent toSave){
         ....
    }

    @SecondTransactional
    public boolean saveToSecondDatabase(ReceivedEvent toSave){
         ....
    }
}

No comments:

Post a Comment