当前位置:网站首页>Error reporting using dynamic multiple data sources under the same transaction

Error reporting using dynamic multiple data sources under the same transaction

2022-06-21 10:47:00 Code knower

Due to the recent project, the database will be divided into multiple databases , From the database of Dangyi , Divide multiple databases according to business , So use dynamic routing +aop To achieve dynamic database switching , When there is an important problem , Is how to solve the problem , Like in one service Query other business databases in , modify , add to , The data source will not be switched , This problem is caused by transactions , As long as you are service Open transaction in ,service Database operations on other businesses in the only use the data source when the transaction is started , Because the data source will be cached after the transaction is started ,service The principal will fetch the data source from the cache , Therefore, the switching of other business data sources fails .

terms of settlement :
Method 1 :
Because this problem is caused by transactions , So start from the business ,spring The propagation level in the transaction annotation can solve this problem ,spring The default propagation level is required Only the current transaction will be used , So in service You have to service Make changes 、 When adding , Need to be in another service Open another new transaction to use required_new Create a new transaction , The data source will be switched , When you're going to talk to another service Start another transaction to use when querying not_supported Master service Hang the transaction in , This will switch the data source .

spring The transaction propagation level of :

REQUIRED: Support current transaction , If there is no current transaction , Just create a new transaction . This is the most common choice .

SUPPORTS: Support current transaction , If there is no current transaction , Just in a non transactional way .

MANDATORY: Support current transaction , If there is no current transaction , Throw an exception .

REQUIRES_NEW: New transaction , If there are currently transactions , Suspend current transaction .
NOT_SUPPORTED: Perform operations in a non transactional way , If there are currently transactions , Suspend the current transaction .

NEVER: To execute in a non transactional manner , If there are currently transactions , Throw an exception .

NESTED: Support current transaction , If the current transaction exists , A nested transaction is executed , If there is no current transaction , Just create a new transaction .

Method 2 :
Business moves to control layer . Do not call different data sources in one implementation method

原网站

版权声明
本文为[Code knower]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202221439119052.html