[英]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.
我如何通过Spring交易实现这一目标。 I've implemented annotation based approach which changes the datasource using AbstractRoutingDataSource.
我已经实现了基于注释的方法,该方法使用AbstractRoutingDataSource更改了数据源。 But, everytime I need to create a new transation using propogation=Requires_New.
但是,每次我需要使用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. 您应该为两个数据存储以及
TransactionManager
bean创建单独的spring配置。 At least one of these beans should have name
value so you can use proper transactional manager when needed: 这些bean中至少有一个应该具有
name
值,因此您可以在需要时使用适当的事务管理器:
@Transactional(transactionManager="DS1transactionManagerBeanName")
// DS1dataStoreRelevant class/method
Of course combining logic which uses both data stores in single transaction is not possible with JpaTransactionManager
. 当然,使用
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). 如果这是您要寻找的内容,则应考虑使用由Web容器(如IBM WebSphere)或其他容器(如Atomikos / Bitronix等)提供的分布式
JtaTransactionManager
,它为您提供了不同数据存储之间的事务性(通常是XA资源)。
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. 在某些情况下(例如Oracle数据存储),一些可能的解决方法是提供从一个数据库到另一个数据库的可见性,并使用单个数据存储/事务管理器,但我不确定它在数据库方面如何工作。
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.
引入带有脏标志等的回滚/重试策略将需要一些额外的逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.