简体   繁体   中英

How to use multiple data-source (one for read and another for write) within a single transaction in Spring?

I have configured two databases. One for read (Read-Only), other for Read-Write operations. I have service which involves both read and write operations. I would like to use the read-only db for all read operations and the other db for write operations. How could I achieve this with Spring transactions. I've implemented annotation based approach which changes the datasource using AbstractRoutingDataSource. But, everytime I need to create a new transation using propogation=Requires_New. Is there a better way to do this?

@DbSource(DbType.READ_REPLICA)
@Transactional(propogation=Requires_New)
public Object readData(long id) {
   return dataDao.find(id);
}

You should create seperate spring configurations for both of your datastores together with TransactionManager beans. At least one of these beans should have name value so you can use proper transactional manager when needed:

@Transactional(transactionManager="DS1transactionManagerBeanName")
// DS1dataStoreRelevant class/method

Of course combining logic which uses both data stores in single transaction is not possible with JpaTransactionManager . If this is what you are looking for you should consider using distributed JtaTransactionManager provided by web container like IBM WebSphere or other like Atomikos/Bitronix etc. which provides you with transactionality between different data stores (XA resources in general).

Some possible workaround in certain cases (like Oracle datastores) would be to provide visibility from one database to other and use single data store/transaction manager but I am not entirely sure how it works underneath on the database side.

The most basic solution would be just to not mix logic impacting each of the data store and arrange it in sequential transactions but as said whole chain of operations won't be transnational itself so possible rollback would apply only to current transaction (no rollback to the ones committed earlier). It would require some extra logic to introduce rollback/retry policy with dirty flags etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM