Multi-database transaction aspect management method and device, equipment and storage medium
By using the transaction section manager to intercept business methods in the financial system, and generating and managing transaction objects of multiple databases, the transaction problem of the existing technology being unable to manage multiple databases in a unified manner, realizing data consistency and business stability.
Patent Information
- Application Number
- CN202411343656.3
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-09-25
- Publication Date
- 2024-12-24
AI Technical Summary
Existing transaction managers cannot manage multiple databases uniformly at the same time, resulting in data inconsistencies that may occur during the data migration of the financial system, affecting the stability and accuracy of business operations.
By determining whether the transaction control annotations are included when the business method is called, using the transaction facet manager to intercept the execution of the business method, generate and store the transaction manager and transaction objects of multiple databases in thread-local variables, monitor the execution status in real time, and successfully Submit transactions when the transaction is, and roll back all transactions when the exception is.
Ensure data consistency between multiple databases, prevent data inconsistency caused by failure of some database transactions, and improve the reliability and stability of data processing in the financial system.
Smart Images

Figure CN119179687A_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the fields of data processing technology and financial technology, and in particular to a multi-database transaction aspect management method, device, equipment and storage medium. Background Art
[0002] In the business systems in the financial field, usually a single business scenario often uses a single database to process data. In this case, the transaction manager provided by the Spring framework can effectively guarantee the transactional operations of the database and ensure data consistency through the commit and rollback mechanism. However, with the advancement of the wave of domestic database replacement, more and more financial systems are facing the transformation and migration of existing databases, especially in the information innovation environment, where the old database and the new database need to run simultaneously for a period of time.
[0003] In the process of migrating data in batches, the system not only needs to interact with the original database, but also needs to operate the newly introduced trust-building database. However, the existing transaction management mechanism is mainly designed for a single database and cannot support unified management of transactions in multiple databases at the same time. This leads to the situation that in some scenarios, although the transaction manager can commit or roll back transactions in a single database, it cannot guarantee transaction consistency across multiple databases. If the system successfully commits a transaction on a certain database, but fails on another database, data inconsistency will occur, which will cause abnormalities in financial business functions and even generate erroneous data, directly affecting the stability and accuracy of business operations.
[0004] The shortcomings of this existing technology are particularly evident when the old database and the trusted database are used in parallel. In particular, when it is necessary to manage the consistency of transactions in multiple databases, the existing transaction manager cannot meet actual needs and cannot coordinate and process transaction operations in a multi-database environment, resulting in business risks for the financial system during the migration process. Summary of the invention
[0005] The main purpose of the present invention is to provide a multi-database transaction aspect management method, device, equipment and storage medium, aiming to solve the technical problem in the prior art that the transaction manager cannot perform unified transaction submission and rollback operations on multiple databases at the same time, which may lead to the generation of erroneous data and affect the normal use of business functions.
[0006] To achieve the above object, the present invention provides a multi-database transaction aspect management method, comprising:
[0007] When calling a business method, determine whether the business method contains annotations for multi-database transaction control;
[0008] If the business method contains annotations for multi-database transaction control, use the transaction aspect manager to intercept the execution of the business method;
[0009] Generate a transaction manager and a transaction object for each database according to the multiple database names specified in the annotation, and store the transaction manager and the transaction object in the ThreadLocal variable of the current thread;
[0010] Execute the business method, and monitor the execution status during the execution of the business method to detect whether an abnormality occurs;
[0011] If the business method is successfully executed, the transaction manager and transaction object are extracted from the ThreadLocal variable, and a commit operation is performed on each transaction in turn;
[0012] If an exception occurs during the execution of the business method, the corresponding transaction manager and transaction object are extracted from the ThreadLocal variable, and the rollback operation is performed one by one to roll back all transactions.
[0013] Furthermore, to achieve the above-mentioned purpose, the present invention provides a multi-database transaction aspect management device, comprising:
[0014] An annotation detection module is used to determine whether the business method contains annotations for multi-database transaction control when calling the business method;
[0015] Aspect interception module, used to intercept the execution of the business method using the transaction aspect manager if the business method contains annotations for multi-database transaction control;
[0016] A transaction initialization module, used to generate a transaction manager and a transaction object for each database according to the multiple database names specified in the annotation, and store the transaction manager and the transaction object in the ThreadLocal variable of the current thread;
[0017] A business execution and monitoring module, used to execute the business method and monitor the execution status during the execution of the business method to detect whether an abnormality occurs;
[0018] A transaction commit module, used to extract the transaction manager and transaction object from the ThreadLocal variable if the business method is successfully executed, and perform a commit operation on each transaction in turn;
[0019] The transaction rollback module is used to extract the corresponding transaction manager and transaction object from the ThreadLocal variable if an exception occurs during the execution of the business method, and perform rollback operations one by one to roll back all transactions.
[0020] Furthermore, to achieve the above-mentioned purpose, the present invention also provides a computer device, which includes a memory, a processor, and a multi-database transaction aspect management program stored in the memory and executable on the processor, and the multi-database transaction aspect management program implements the steps of the multi-database transaction aspect management method as described above when executed by the processor.
[0021] Furthermore, to achieve the above-mentioned purpose, the present invention also provides a computer-readable storage medium, on which a multi-database transaction aspect management program is stored, and when the multi-database transaction aspect management program is executed by a processor, the steps of the multi-database transaction aspect management method as described above are implemented.
[0022] Beneficial effects: The present invention relates to the field of data processing technology, and discloses a multi-database transaction aspect management method. When calling a business method, it is determined whether a multi-database transaction control annotation is included. When the annotation exists, the business method is intercepted by a transaction aspect manager, and a transaction manager and transaction objects corresponding to multiple databases are created, and these objects are stored in thread local variables. During the execution process, the execution status of the business method is monitored in real time to detect whether an exception occurs. After the business method is successfully executed, the transaction manager is extracted from the thread, and the commit operation is performed in sequence. If an exception occurs, a rollback operation is performed to ensure that the transactions of all databases are restored to the initial state. The present invention can effectively solve the problem that the existing transaction manager cannot manage multiple databases at the same time by generating multiple transaction managers and transaction objects in a multi-database environment and using the transaction aspect manager for unified management. By storing the transaction manager and transaction objects in thread local variables, each thread can independently manage its corresponding transaction, thereby avoiding data pollution between threads. By unified submission of transactions and rollback operations in the event of an exception, data consistency between multiple databases is ensured, and data inconsistency caused by failure to submit transactions of some databases is prevented. BRIEF DESCRIPTION OF THE DRAWINGS
[0023] The present invention will be further described below with reference to the accompanying drawings and embodiments, in which:
[0024] Figure 1 A schematic diagram of an application environment of a multi-database transaction aspect management method according to an embodiment of the present invention;
[0025] Figure 2 A schematic diagram of a process flow of an embodiment of a multi-database transaction aspect management method of the present invention;
[0026] Figure 3 It is a functional module diagram of a preferred embodiment of the multi-database transaction aspect management device of the present invention;
[0027] Figure 4 A schematic diagram of the structure of a computer device in one embodiment of the present invention;
[0028] Figure 5 FIG. 4 is another schematic diagram of the structure of a computer device in one embodiment of the present invention. DETAILED DESCRIPTION
[0029] It should be understood that the specific embodiments described herein are only used to explain the present invention, and are not used to limit the present invention.
[0030] The multi-database transaction aspect management method provided by the embodiment of the present invention can be applied in the following aspects: Figure 1 In an application environment, the client communicates with the server through a network. The server can obtain the metadata of the business method through the reflection mechanism of the client to determine whether it contains multi-database transaction control annotations. When the annotation exists, the business method is intercepted by the transaction aspect manager, and the transaction manager and transaction objects corresponding to the multiple databases are created, and these objects are stored in thread local variables. During the execution process, the execution status of the business method is monitored in real time to detect whether an exception occurs. After the business method is successfully executed, the transaction manager is extracted from the thread and the commit operation is performed in sequence. If an exception occurs, a rollback operation is performed to ensure that the transactions of all databases are restored to the initial state. The present invention can effectively solve the problem that the existing transaction manager cannot manage multiple databases at the same time by generating multiple transaction managers and transaction objects in a multi-database environment and using the transaction aspect manager for unified management. By storing the transaction manager and transaction objects in thread local variables, each thread can independently manage its corresponding transaction, thereby avoiding data pollution between threads. By unified submission of transactions and rollback operations in the event of an exception, data consistency between multiple databases is ensured, and data inconsistency caused by failure to submit transactions of some databases is prevented. The client may be, but is not limited to, various personal computers, laptops, smart phones, tablet computers, and portable wearable devices. The server may be implemented by an independent server or a server cluster consisting of multiple servers. The present invention is described in detail below through specific embodiments.
[0031] See also Figure 2 , Figure 2 This is a flow chart of an embodiment of a multi-database transaction aspect management method provided by the present invention. It should be noted that although a logical sequence is shown in the flow chart, in some cases, the steps shown or described may be performed in a different order than that shown here.
[0032] like Figure 2 As shown, the multi-database transaction aspect management method proposed by the present invention includes the following steps:
[0033] S10, when calling a business method, determining whether the business method contains an annotation for multi-database transaction control;
[0034] In this embodiment, in a financial business scenario or other distributed system, the business system will call business methods in specific situations, usually when a user operates or the system triggers a business process. For example, when a user performs an inter-bank transfer or involves multiple account operations at the same time, the system will call the business method related to the business scenario. Business methods are usually the implementation of the core business logic of the system, and may involve operations on multiple databases during execution. The system needs to ensure that it is ready for transaction processing when called.
[0035] A business method is a code that executes specific business logic in a business system or application. It usually contains specific operations to complete a certain business process, involving data processing, transaction management, calculation, etc. A business method may be called multiple times in a complete system to respond to user requests, process transactions, or generate specific business results.
[0036] Business methods usually contain the core logic of business processes, such as order processing, fund transfer, inventory management, etc. Their purpose is to achieve specific business functions.
[0037] In many cases, business methods need to support transaction management, especially when database operations are involved. For example, in a bank transfer business method, you need to ensure that no data inconsistencies occur during the funds transfer process.
[0038] Business methods are usually modular and support reuse in multiple scenarios. For example, the deduction operation in the payment system can be called multiple times by different payment processes.
[0039] Example description:
[0040] In a banking system, a business method that handles a money transfer might include the following logic:
[0041] Verify that the transfer request is legitimate.
[0042] Check whether the account balance is sufficient.
[0043] Deduct the initiator's account balance and update the database.
[0044] Increase the recipient's account balance and update the database.
[0045] When a business request is initiated, the system calls the relevant business methods through the established process. For example, the system will schedule the methods in the business logic execution layer based on the data or operation instructions entered by the user. These methods can be synchronous calls or asynchronous tasks.
[0046] The system needs to determine whether a business method is associated with a multi-database transaction operation. At this point, the system determines this by identifying whether the business method contains a specific transaction control annotation (such as a multi-database transaction control annotation). This annotation will clearly specify whether the business method involves transaction operations in multiple databases. Annotations are usually used to identify metadata for business methods, and the system can decide whether to enable a specific transaction management process based on the annotation information at runtime.
[0047] When the system calls a business method, it can determine the nature of the method through metadata or by directly reading the annotation content. In some cases, annotations can be defined by the developer through configuration or at compile time. In the Spring framework, this process can be implemented through aspect programming (AOP) and annotation-driven methods. Spring's @Transactional annotation can be used as an annotation for multi-database transaction control. The system determines the need for transaction control through annotation identification. If the transaction control annotation is marked, the system will enter the transaction management logic.
[0048] Example: In a financial institution, when a user initiates a cross-account transfer request, the system needs to perform the transfer and balance update operations in two different databases:
[0049] Account A's database: stores the user's account balance and transaction records;
[0050] Account B's database: stores the payee's account information and transaction records.
[0051] During the transfer operation, the system will call the business method to operate the two databases at the same time. If the business method is marked with a multi-database transaction control annotation, the system will determine that the operation involves multiple databases and then start multi-database transaction management. The transaction manager will ensure that the update operations of account A and account B are executed as a whole. If the operation is successful, the system will commit the transactions of the two databases; if the operation fails, all transactions will be rolled back to ensure the consistency of account balances and transaction records and avoid the risk of incorrect fund transfers.
[0052] By detecting whether multi-database transaction control annotations are included when calling business methods, the system can automatically identify and handle business scenarios that require multi-database transaction management. This improves the flexibility of the system, avoids hard-coded logic, and ensures unified transaction processing across multiple databases, avoiding data inconsistencies, thereby improving business reliability and data integrity.
[0053] S20, if the business method contains annotations for multi-database transaction control, use a transaction aspect manager to intercept the execution of the business method;
[0054] In this embodiment, in the Spring framework, the transaction aspect manager is a transaction management tool based on Spring AOP (aspect-oriented programming), which is used to dynamically insert transaction control logic before or after the execution of a business method. Its core function is to start a transaction before executing the method according to the annotation of the business method (such as @Transactional), commit the transaction after the method is successfully executed, and roll back the transaction when the method fails or is abnormal. Through Spring's AOP mechanism, the transaction aspect manager can intercept the execution of the business method and add transaction control logic to it. This is very important for scenarios that need to span multiple databases or need to ensure data consistency.
[0055] The components of the transaction aspect manager include:
[0056] Pointcut: used to define which business methods should be intercepted and the transaction logic should be applied. It can be defined through annotations or configuration files.
[0057] Advice: used to insert transaction logic before or after the execution of the business method defined by the pointcut, including starting a transaction, committing a transaction, rolling back a transaction, etc.
[0058] Transaction Manager: A specific transaction processor used to manage transactions for database operations. The transaction manager can control the life cycle of transactions, including transaction initiation, commit, and rollback.
[0059] Dynamic Proxy: Through the dynamic proxy mechanism of SpringAOP, the transaction aspect manager can dynamically intercept and process the execution of business methods.
[0060] Aspect-based programming (AOP) allows you to add additional logic before or after a business method is executed. If a business method contains annotations for multi-database transaction control, Spring AOP can intercept the method when it is called and execute specific transaction management logic.
[0061] When the system detects that a business method contains annotations for multi-database transaction control, AOP technology triggers the interceptor (aspect) and binds the business method to the multi-database transaction management function through the definition of the pointcut.
[0062] Define an aspect class through Spring's @Aspect annotation, which is responsible for intercepting all methods annotated with multi-database transaction control annotations. Use the @Pointcut annotation to define a pointcut, and the pointcut expression identifies the business method that requires transaction management based on the annotation. Before the business method is executed, the pre-notification starts the transaction management; after the method is executed, the post-notification commits or rolls back the transaction.
[0063] Pointcuts are used to specify which business methods will be intercepted by aspects. By defining pointcuts, SpringAOP can accurately identify methods containing multi-database transaction control annotations and automatically trigger transaction management logic when these methods are executed. Pointcuts determine whether to enable transaction management based on the presence of annotations.
[0064] Use Spring AOP's expression language (such as execution() or @annotation()) to define a pointcut that matches all methods containing specific annotations. When a qualified business method is called, Spring AOP intercepts the method and executes the predefined transaction logic.
[0065] Example description:
[0066] In financial systems, some business operations may involve the linkage of multiple databases. For example, in a cross-bank transaction scenario, the transfer operation involves not only the database of the user's bank, but also the databases of other partner banks. At this time, by adding multi-database transaction control annotations to the business methods, the system can use SpringAOP technology to automatically intercept these cross-database transfer methods.
[0067] Specifically, when a user submits an inter-bank transfer request, the system automatically calls a business method annotated with a multi-database transaction annotation. SpringAOP intercepts the method through aspects and initializes the transaction managers of different databases before executing the method. When all transfer steps are successfully completed, the system commits transactions in all databases to ensure data consistency. If any step fails, all database operations will be rolled back to avoid fund errors or data inconsistencies. This mechanism ensures fund security and data consistency in the financial system.
[0068] Through Spring's aspect programming technology, the system can dynamically intercept business methods annotated with multi-database transaction control annotations to ensure that these methods trigger transaction management logic when executed. This mechanism effectively avoids hard-coded transaction management methods and enhances the flexibility and scalability of the system. In multi-database scenarios, the system can automatically implement transaction consistency control to prevent data inconsistency problems, thereby improving the security and reliability of transaction management.
[0069] S30, generating a transaction manager and a transaction object for each database according to the multiple database names specified in the annotation, and storing the transaction manager and the transaction object in a ThreadLocal variable of the current thread;
[0070] In this embodiment, when a business method is annotated with an annotation for multi-database transaction control, multiple database names are usually specified in the annotation. The system needs to read these database names for subsequent transaction manager generation and transaction processing. Each database name corresponds to a different database instance, and the system locates the specific database based on these names so that transaction managers can be independently generated on different databases.
[0071] The system parses the annotations on the business method and extracts the database name list in the annotation. The list can be a parameter value of the annotation. The system parses the annotation object and reads the parameter to determine the database name.
[0072] Based on the extracted database names, the system generates a corresponding transaction manager for each database instance. The transaction manager is used to manage transaction commit, rollback and other operations of the database. The transaction object is the key to transaction management. It records the status of the transaction and provides a transaction commit or rollback mechanism.
[0073] Use Spring's DataSourceTransactionManager class to dynamically create multiple transaction managers based on the name of each database. Call the getTransaction() method of each transaction manager to generate a transaction object corresponding to the database, ensuring the independence of the transaction management object.
[0074] Each thread needs to manage the state of the transaction independently to prevent transaction information between multiple threads from interfering with each other. ThreadLocal variables allow each thread to save the transaction manager and transaction objects in its own context to ensure thread independence. ThreadLocal ensures that each thread holds its own independent transaction manager and transaction object to avoid data pollution between threads.
[0075] Store each transaction manager and transaction object in the ThreadLocal of the current thread to ensure thread isolation. Use the ThreadLocal.set() method to bind the transaction manager and transaction object to the thread, so that each thread can manage its own transactions independently.
[0076] Example: A customer initiates an inter-bank transfer request. The system needs to perform the following operations in multiple databases:
[0077] In the customer's bank database, the transfer amount is deducted, the customer's account balance is updated, and the transaction is recorded. In the receiving bank's database, the recipient's account balance is increased and the transaction is also recorded. These two operations need to be completed at the same time. If either fails, all operations need to be rolled back to ensure data consistency. If the customer bank's operation succeeds and the receiving bank's operation fails, it will lead to inconsistent account balances and fund errors. This situation must be handled through multi-database transaction management.
[0078] The multi-database transaction control annotation is marked on the business method, and the method involves the databases of both the client bank and the receiving bank. When the system calls the business method, it generates a separate transaction manager for each database based on the database name in the annotation to ensure that the transactions of the two banks are managed separately.
[0079] Through Spring aspect programming technology, the system intercepts the business method before and after the method is executed, starts the transaction manager, and ensures the consistency of database transactions.
[0080] If the business method is executed successfully, the system will extract the transaction manager from ThreadLocal and commit the transactions of each database in turn; if an exception occurs, the system will roll back the transactions of the two databases in turn to ensure that no financial errors occur.
[0081] By generating independent transaction managers based on the multiple database names specified in the annotation and storing these managers and transaction objects in ThreadLocal, the system can manage transaction consistency in multi-database scenarios, prevent data pollution between threads, ensure the independence and integrity of transactions, and thus avoid data inconsistency problems in cross-database operations.
[0082] S40, executing the business method, and monitoring the execution status during the execution of the business method to detect whether an abnormality occurs;
[0083] In this embodiment, the actual business method is executed in the context of transaction management. In the transaction management process, the execution of the business method is a key step that determines the success of the transaction. The goal of this step is to call the specified business logic and complete the required data operations in a multi-database transaction environment.
[0084] In the business system, when the transaction manager is initialized, the system calls the business method marked with multi-database transaction control annotations. The business method can be any function involving data operations, such as fund transfer, data update, etc. The execution process occurs in a pre-configured transaction environment, ensuring that the execution of the business method is subject to transaction control, especially in cross-database operations.
[0085] The transaction manager needs to monitor the execution status of the business method in real time to ensure that any exceptions or error information can be captured during the execution process. The purpose of monitoring is to detect whether the business method is completed as expected, including runtime exceptions or data processing errors that occur midway.
[0086] Business methods are wrapped in try-catch structures or monitored through Spring's TransactionSynchronization mechanism. During method execution, the monitor (or transaction manager) captures the execution status of the business method in real time. The status includes the start, execution, commit, or rollback of the transaction. The monitor can also track other performance indicators such as method execution time and memory usage.
[0087] Anomaly detection is a key link in transaction management. If any anomalies occur during the execution of a business method (such as database access anomalies, network timeouts, etc.), the system needs to detect these anomalies and trigger a transaction rollback operation to ensure data consistency.
[0088] In the try-catch structure of the business method, catch RuntimeException or other custom exceptions. The system can automatically trigger exception detection through the exception handling mechanism of TransactionManager. Once an exception is detected, the transaction is rolled back immediately to avoid submitting inconsistent data. The exception recording system will record the exception information in the log or monitoring system for subsequent analysis and troubleshooting.
[0089] Example description:
[0090] In the financial system, business operations such as fund transfer and loan approval usually involve the synchronization of multiple databases. Take inter-bank transfer as an example. When a customer initiates an inter-bank transfer request, the system will deduct funds from the customer's bank's database and add funds to the recipient bank's database. The entire transfer process involves two different databases.
[0091] When executing the transfer business method, the system first monitors the deduction and addition operations through the transaction manager. After the deduction is successful, the system continues to add the funds. If a network timeout or a failure in the receiving bank database occurs at this time, the transaction manager will detect the anomaly and immediately terminate the entire transfer process, roll back the transaction that has been deducted, and ensure that the funds are not deducted from the customer's account. Through this mechanism, the financial system can effectively avoid the loss of funds or data inconsistency caused by the failure of some operations, and ensure that each financial operation can remain safe when an anomaly occurs.
[0092] This real-time exception monitoring mechanism ensures the security and reliability of financial data processing, greatly reduces the risks brought by abnormal situations in the system, and enhances the transparency and control capabilities of financial business operations.
[0093] By monitoring the status of business methods in real time when they are executed and detecting whether anomalies occur, the system can ensure that any errors can be captured and handled in a timely manner in a multi-database transaction environment. This mechanism not only enhances the robustness of transaction management, but also prevents data inconsistencies and operational errors, ensuring the security and consistency of business operations, especially when processing large-scale financial transactions, reducing the impact of errors on the system and customers.
[0094] S50, if the business method is successfully executed, extract the transaction manager and transaction object from the ThreadLocal variable, and perform a commit operation on each transaction in turn;
[0095] In this embodiment, when the business method is successfully executed, it means that the business logic processing is successfully completed without throwing any exceptions, and the transaction can be safely submitted. In a multi-database transaction environment, transactions of multiple databases need to be submitted in a coordinated manner to ensure that data operations in all databases can be successfully applied.
[0096] When a business method goes through all the steps during execution and returns a success flag, the transaction manager needs to extract the corresponding transaction manager and transaction object from ThreadLocal and prepare to execute the transaction commit operation. The success status of the business method can be judged by the return value or no exception thrown.
[0097] ThreadLocal is a mechanism to ensure thread-local storage variables, providing each thread with independent storage space in a multi-threaded environment. The transaction manager and transaction objects of each database are stored in the ThreadLocal of the current thread when the business method is executed, ensuring that each thread can handle its transactions independently.
[0098] The transaction manager and transaction object are created and stored in ThreadLocal when the business method starts executing. When the method is executed successfully, the transaction manager and transaction object of each database are retrieved in turn by calling the ThreadLocal.get() method, and the commit operation is prepared for each transaction.
[0099] Each database has its own transaction manager and transaction object. The commit() operation will make the changes to the database persistent. The transaction commit operation ensures that all modified data is applied and eventually written to the database. In a multi-database scenario, transaction commits need to be executed one by one to ensure that transactions in all databases are consistent.
[0100] Call the commit() method of each extracted transaction manager to commit database transactions one by one. If all transactions are successfully committed, the data is officially persisted to each database; if the commit fails, other processing measures may be taken according to the specific implementation.
[0101] Example description:
[0102] In the financial system, cross-bank transactions involving multiple databases are very common. For example, when a customer initiates an inter-bank payment, the system needs to perform data update operations in the databases of both the customer bank and the receiving bank. The entire process includes the deduction and addition of funds, involving synchronous transaction processing of two databases.
[0103] When the payment operation is successfully completed, the system extracts the transaction managers of the customer bank and the receiving bank from ThreadLocal and calls the commit() method one by one to ensure that the database changes of both banks are committed. This mechanism ensures the consistency of payment operations in all relevant databases, avoiding fund loss or data inconsistency. If the commit() operation of any party fails, the system will take remedial measures according to the rollback strategy to prevent the risk of incorrect fund transfer. This mechanism enables the financial system to effectively handle transaction submission in a multi-database environment, ensuring data consistency and fund security across systems.
[0104] By extracting the transaction manager from ThreadLocal after the business method is successfully executed and performing commit operations in sequence, the system can ensure that transactions of all databases are consistently committed in multi-database scenarios. This effectively solves the problem of multi-database transaction consistency, avoids data inconsistency caused by failure to commit some transactions, and improves the data reliability and security of the system during cross-database operations.
[0105] S60, if an exception occurs during the execution of the business method, extract the corresponding transaction manager and transaction object from the ThreadLocal variable, perform rollback operations one by one, and roll back all transactions.
[0106] In this embodiment, when executing a business method, an exception may occur due to network errors, database failures, timeouts, etc. When an exception occurs, the business method cannot be successfully executed, and the system needs to handle transaction management to prevent data inconsistency. The exception can be detected through the try-catch mechanism or other monitoring tools. When an exception is detected, the transaction manager needs to perform a rollback operation to cancel the transaction.
[0107] If an exception is encountered during the execution of a business method, the system will capture the exception through try-catch or other exception monitoring tools. After catching the exception, the system enters the exception handling process and prepares to roll back the transaction to prevent some transaction operations from being committed.
[0108] Before the business method is executed, the transaction manager and transaction object are stored in the ThreadLocal variable of the current thread to ensure the isolation and consistency of the transaction. When an exception occurs in the business method, the system needs to extract these transaction managers and transaction objects from ThreadLocal and perform a rollback operation. ThreadLocal is used to ensure that each thread has its own independent transaction management context in a multi-threaded environment.
[0109] The system uses the ThreadLocal.get() method to extract the transaction manager and transaction object corresponding to the business method from the current thread to ensure that the transaction can be rolled back in abnormal situations. The transaction manager is responsible for managing the state of the transaction, and the transaction object records the detailed information of the transaction, including the current transaction state (such as started, rolled back, etc.).
[0110] The purpose of transaction rollback is to ensure that when an exception occurs, all database operations can be undone and restored to the state before the transaction started. The transaction manager of each database is responsible for rolling back the database operations. The purpose of performing rollback operations one by one is to ensure that transactions of multiple databases can be rolled back independently without affecting the state of other databases.
[0111] The system traverses the transaction managers extracted from ThreadLocal in turn, calling the rollback() method to roll back the changes in the transaction. The rollback() method of each transaction manager undoes all database operations during the transaction and restores the database to the state at the beginning of the transaction.
[0112] Example description:
[0113] In financial systems, the need for multi-database transaction management is very common. For example, in inter-bank fund transfers, the system needs to update database records of multiple banks at the same time. Assuming that the operation in one bank is successful, but the database operation in other banks fails, the system must roll back the operation in all databases to ensure the consistency of fund transfers.
[0114] Specifically, when executing the business method of fund transfer, if the system detects an abnormality in a bank's database (such as network disconnection or database timeout), the system will extract the relevant transaction manager from ThreadLocal and roll back all bank database operations one by one to prevent some operations from being submitted successfully while other operations fail. This multi-database rollback mechanism ensures the consistency of financial data, avoids incorrect fund flows, and protects the security of customer accounts.
[0115] By extracting the transaction manager from ThreadLocal and performing rollback operations one by one when an exception occurs in a business method, the system can effectively avoid data inconsistency problems in abnormal situations. It ensures that when a transaction fails, all related database operations will be revoked, ensuring the integrity and consistency of the transaction, thereby improving the reliability of the system, which is especially suitable for multi-database transaction management scenarios.
[0116] The invention relates to the technical field of data processing, and discloses a multi-database transaction aspect management method. The metadata of a business method is obtained through a reflection mechanism to determine whether it contains a multi-database transaction control annotation. When the annotation exists, the business method is intercepted by a transaction aspect manager, and a transaction manager and a transaction object corresponding to multiple databases are created, and these objects are stored in thread local variables. During the execution process, the execution state of the business method is monitored in real time to detect whether an exception occurs. After the business method is successfully executed, the transaction manager is extracted from the thread, and the commit operation is performed in sequence. If an exception occurs, a rollback operation is performed to ensure that the transactions of all databases are restored to the initial state. The invention can effectively solve the problem that the existing transaction manager cannot manage multiple databases at the same time by generating multiple transaction managers and transaction objects in a multi-database environment and using the transaction aspect manager for unified management. By storing the transaction manager and the transaction object in the thread local variable, each thread can independently manage its corresponding transaction, thereby avoiding data pollution between threads. By unified submission of transactions and rollback operations in the event of an exception, data consistency between multiple databases is ensured, and data inconsistency caused by failure to submit transactions of some databases is prevented.
[0117] In one embodiment, the above S10 includes:
[0118] S101, when a business method is called, the reflection mechanism is used to obtain metadata of the business method, where the metadata includes the method name, parameter type, and annotation information;
[0119] S102, scanning all annotation information of the business method to obtain a list of annotations marked on the business method;
[0120] S103, by traversing the annotation list, using the isAnnotationPresent method to determine whether the business method contains an annotation for multi-database transaction control;
[0121] S104: If the business method is not marked with an annotation for multi-database transaction control, check whether the parent class or interface of the business method contains an annotation for multi-database transaction control.
[0122] In this embodiment, the reflection mechanism allows the system to dynamically obtain metadata information of the class at runtime, such as method name, parameter type, and annotation information. When calling a business method, the reflection mechanism is used to retrieve detailed information of the business method, including method name, parameters, and whether annotations are included. In this way, the system does not need to determine the specific properties of the method at compile time, but can flexibly obtain the required metadata information through dynamic analysis through reflection at runtime.
[0123] Using the Java reflection API, first obtain the Method object of the business method, call getName() to obtain the method name, call getParameterTypes() to obtain the parameter type. Then, call getAnnotations() to obtain all annotation information of the method to determine whether there are annotations for multi-database transaction control.
[0124] The purpose of scanning all annotation information of a business method is to fully understand whether the method is annotated with certain transaction control annotations. Annotations are a way to identify metadata, usually used to tell the system that the method requires special processing (such as transaction control, permission verification, etc.). By traversing the annotation information, the system can flexibly handle different annotations on the method and identify whether it contains annotations related to transaction control.
[0125] By calling the getDeclaredAnnotations() method, the system can obtain all annotations marked on the method and store them in the annotation list. Then, the system traverses these annotations to check whether they contain annotations related to multi-database transaction control.
[0126] The annotation list may contain multiple annotations. The system checks whether there are annotations related to multi-database transaction control by traversing the annotation list one by one. The isAnnotationPresent method is a convenient way to determine whether a specified annotation exists. When a specific transaction control annotation is detected, the system will decide whether to enable transaction management based on this information.
[0127] Traverse each annotation in the annotation list and call the isAnnotationPresent(Class<? extendsAnnotation> annotationClass) method. If the annotation exists, it returns true and the system will perform transaction management; otherwise, continue to check the annotations in the parent class or interface.
[0128] If the business method itself is not annotated with multi-database transaction control annotations, the system will check whether there are relevant annotations in the parent class or interface of the method. This check ensures that even if the business method is not explicitly annotated, the system can detect whether there is relevant transaction control logic in the inherited or implemented class.
[0129] If isAnnotationPresent() does not find the annotation in the current method, the system will get the parent class through the getSuperclass() method and check whether the parent class method contains the annotation. Similarly, by calling the getInterfaces() method to traverse the interface, the system will also check the annotation information in the interface to ensure that no transaction control annotation is missed.
[0130] In object-oriented programming, inheritance is a core mechanism for sharing and reusing code. Methods and properties in a parent class can be inherited by child classes, while interfaces define the behaviors that a class must implement. By inheriting or implementing an interface, a child class can inherit the annotations and logic defined in the parent class or interface.
[0131] A business method may not be annotated directly, but its parent class or interface may have annotated some methods with transaction control related annotations. In order to ensure that the transaction management of the subclass business method is not ignored, the system needs to check the annotations in the parent class and interface to automatically identify and apply multi-database transaction control.
[0132] In many scenarios, developers use inheritance to reduce code redundancy. The parent class or interface has already been annotated with annotations related to transaction management, and the subclass does not need to repeat the same annotations. In order to keep the code concise, the subclass usually depends on the existing logic of the parent class or interface. Checking the annotations in the parent class or interface can avoid the need for the subclass to repeat the same annotations, thereby simplifying code management.
[0133] An interface is a design contract that specifies the functionality that an implementation class must have. Interface methods usually do not contain specific implementations, but the interface designer can annotate the methods with some metadata (such as transaction control annotations) to ensure that each implementation class meets specific requirements when executing these methods. If a class implements an interface and the interface method contains transaction control annotations, the system should consider the transaction control logic in the interface when calling the class method. By checking the annotations in the interface, the system can ensure that the methods in the implementation class are also suitable for transaction control.
[0134] As the complexity of the system increases, transaction control annotations defined in parent classes or interfaces can provide a unified and scalable way of managing transactions for future business methods. Developers can define common transaction control logic in parent classes or interfaces to ensure that each subclass method follows consistent transaction management rules. Checking annotations in parent classes and interfaces can ensure that subclasses and implementation classes can automatically inherit these transaction management rules, thereby achieving greater scalability and consistency. In this way, even if subclasses or implementation classes are not explicitly annotated, they can still enjoy transaction management capabilities based on the parent class or interface.
[0135] In some business scenarios, ensuring the consistency and correct management of transactions is crucial. The transaction control annotations of the parent class or interface may have defined the necessary transaction processing logic for the subclass. By checking the annotations in the parent class and interface, the system can avoid missing some critical transaction control logic and ensure that transactions can be correctly managed and rolled back when the subclass method is executed.
[0136] This embodiment obtains the metadata of the method through the reflection mechanism, scans the annotations and determines whether it contains multi-database transaction control annotations. The system can flexibly and dynamically detect whether the business method requires transaction management without determining the attributes of the method at compile time. This mechanism avoids hard coding and cumbersome configuration, allowing the system to flexibly adjust the transaction management strategy at runtime, especially in a multi-database environment, ensuring the consistency and integrity of data operations.
[0137] In one embodiment, the above S20 includes:
[0138] S201, using the transaction aspect manager to define a pointcut for identifying multi-database transaction control annotations by configuring an interception point;
[0139] S202, using expression language to set a cut point to intercept business methods annotated with multiple database transaction control annotations;
[0140] S203, before the business method is executed, the aspect logic is started through the pre-notification;
[0141] S204, when the business method is called, the execution of the business method is intercepted through the defined pointcut;
[0142] S205, when intercepting the business method, parsing the multi-database transaction control annotation marked on the business method, and extracting parameter information in the annotation;
[0143] S206, after intercepting the business method, executing a predefined aspect operation, and initializing a transaction management operation based on the parameter information in the annotation;
[0144] S207, controlling the execution process of the business method through dynamic proxy, and determining the execution order according to the logic of transaction management.
[0145] In this embodiment, the transaction logic in the business method is managed through aspect programming (AOP) technology. The transaction aspect manager can automatically intercept certain business methods and add transaction control logic to these methods, including transaction start, commit and rollback. It is responsible for ensuring the consistency of database operations according to business requirements.
[0146] Interception points (also called cut points) are rules that define which business methods should be intercepted by aspects. By configuring interception points, you can tell the transaction aspect manager on which methods to apply transaction management. The configuration method can specify which methods or classes to intercept through annotations, XML configuration, or expression language.
[0147] The purpose of pointcuts is to identify business methods annotated with multi-database transaction control annotations. In this way, only methods with complex transaction logic involving multiple databases will be intercepted and the corresponding transaction management rules will be applied.
[0148] In Spring AOP (Aspect-Oriented Programming), pointcuts are used to specify which business methods will be intercepted. In order to intercept methods annotated with multiple database transaction control annotations, you need to define a pointcut in Spring AOP through the @Pointcut annotation or using XML configuration. This pointcut is specifically used to identify business methods annotated with specific transaction control annotations.
[0149] Define the pointcut through the @Pointcut annotation, and use expressions to identify the multiple database transaction control annotations in the business method, such as @annotation(com.example.MultipleDatabaseTransaction). Alternatively, use Spring's XML configuration file to define the same pointcut rules.
[0150] SpringAOP defines pointcuts using expression language. Expressions can be defined based on annotations, method names, package structures, and other conditions. Expressions specifically intercept business methods that contain multi-database transaction control annotations. Use expression language to define pointcuts in @Pointcut, such as @annotation(com.example.MultipleDatabaseTransaction). Ensure that all methods marked with this annotation are intercepted and enter the transaction management process when they are called.
[0151] Before advice (@Before) is an AOP operation that is executed before the business method is executed. Through before advice, you can start the transaction management logic before the business method is executed, ensuring that the transaction manager is properly initialized before the method is actually executed. Define before advice with SpringAOP's @Before annotation to start transaction management. In the before advice, you can initialize the transaction manager and related resources to ensure that the business method is executed in a transaction environment.
[0152] When a business method is called, the defined pointcut intercepts the execution of the method and triggers the transaction management logic. Pointcut interception ensures that the system automatically performs transaction processing every time a business method annotated with transaction control annotations is called. When a business method is called, Spring AOP intercepts the method and triggers the AOP logic to enter the transaction management process.
[0153] After intercepting the business method, the system needs to parse the annotations on the method and extract the parameter information required for multi-database transaction management (such as database name, transaction configuration, etc.) from the annotations. Use the reflection mechanism to parse the annotations on the business method and extract parameters such as multiple database names in the annotations. These parameters are used to initialize the corresponding database transaction manager.
[0154] Based on the parameters specified in the annotation (such as database name, transaction propagation properties, etc.), the system initializes a separate transaction manager for each database. Each transaction manager is responsible for managing transactions for a specific database, ensuring that multiple database transactions can be committed or rolled back independently. Multiple DataSourceTransactionManager instances are initialized by the database name. Transaction objects are generated for each database and stored in ThreadLocal to ensure thread isolation of transactions.
[0155] Dynamic proxy allows the system to insert transaction management logic when business methods are executed. Through the proxy, the system can control the execution flow of business methods and determine the order of transaction commit or rollback based on the transaction management logic. Use SpringAOP's dynamic proxy mechanism to wrap business methods. Start the transaction manager before the business method is executed, commit the transaction after the method is successfully executed, and roll back the transaction if an exception occurs.
[0156] In this embodiment, through the Spring aspect programming technology, the system can automatically intercept business methods with multi-database transaction control annotations to ensure that each business call goes through the transaction management process. This annotation-based transaction management greatly simplifies the work of developers and avoids manually writing cumbersome transaction control codes. Through dynamic proxy, the system can flexibly control the execution process of business methods, ensure the consistency of multi-database transactions, avoid the risk of data inconsistency and transaction failure, and improve the stability and scalability of the system.
[0157] In one embodiment, the above S30 includes:
[0158] S301, obtaining multi-database transaction control annotation instances on business methods through a reflection mechanism;
[0159] S302, parsing the database name field in the annotation instance, and constructing a list containing multiple database names;
[0160] S303, traversing the list including the names of multiple databases, and processing each database one by one;
[0161] S304, calling the DataSource in the Spring container to obtain the corresponding data source according to each database name;
[0162] S305, using the DataSource of each database, initialize the corresponding transaction manager;
[0163] S306, setting transaction attributes for each transaction manager, wherein the transaction attributes include propagation behavior and isolation level;
[0164] S307, calling the getTransaction method of the transaction manager, generating a transaction object for each database, and recording the start status of the transaction;
[0165] S308, storing the transaction manager and corresponding transaction object of each database in the ThreadLocal variable of the current thread.
[0166] In this embodiment, the system calls the reflection API and obtains all annotations on the business method through the Method.getAnnotations() method, and traverses the obtained annotation instances to find annotations related to multi-database transaction control.
[0167] By parsing the parameter fields in the annotation, the system can extract all the database names that need to be processed. An annotation usually specifies multiple database names, which correspond to different database instances. From the obtained annotation instance, call the annotation's get() method to extract the database name field. Build a list containing multiple database names, each name in the list corresponds to a different database.
[0168] In order to ensure transaction management for each database, the system needs to process each database in the list in turn. The traversal process is to ensure that each database generates an independent transaction manager and transaction object. Use a for loop to traverse the database name list and process the transaction initialization and management operations of each database one by one.
[0169] The DataSource interface in the Spring framework is used to obtain database connections. Each database name corresponds to a different DataSource instance, and the system manages these data sources through the Spring container. The system uses the database name to obtain the corresponding DataSource instance through the ApplicationContext.getBean() method. Each database name corresponds to a specific DataSource instance, ensuring connection management for multiple databases.
[0170] Each database's DataSource is associated with an independent transaction manager. The DataSourceTransactionManager class is responsible for managing transaction commits, rollbacks, and other operations. Use the DataSourceTransactionManager class to generate a transaction manager instance for each database's DataSource, ensuring that each database has an independent transaction manager.
[0171] Transaction attributes include propagation behavior and isolation level. Propagation behavior determines whether the current transaction can join an existing transaction or must create a new transaction. Isolation level defines how different transactions avoid interfering with each other. For each transaction manager, call setPropagationBehavior() to set the propagation behavior and setIsolationLevel() to set the isolation level of the transaction.
[0172] The transaction object is responsible for managing the status of the current transaction (such as active, committed, and rolled back). By calling the getTransaction() method, a transaction object associated with the current transaction manager is generated. The getTransaction() method is called for each transaction manager to generate a transaction object associated with it. The start status of the transaction is recorded to prepare for subsequent transaction commits or rollbacks.
[0173] ThreadLocal is a mechanism for storing thread-independent variables. In the transaction management process, using ThreadLocal can ensure that each thread independently maintains its transaction manager and transaction object to avoid data interference between different threads. Calling the ThreadLocal.set() method stores the transaction manager and transaction object in the ThreadLocal variable of the current thread, ensuring that the transaction manager and object of each thread are stored independently.
[0174] This embodiment extracts multiple database names from the annotation and generates independent transaction managers and transaction objects for each database, so that the system can achieve transaction consistency management in a multi-database environment. The ThreadLocal mechanism ensures that each thread manages its transactions independently to avoid interference between threads. This improves the flexibility of the system in multi-database scenarios, ensures transaction independence and data consistency, and prevents the risk of data inconsistency or transaction failure.
[0175] In one embodiment, the above S40 includes:
[0176] S401, putting the business method into a try-catch structure;
[0177] S402, before executing the business method, initializing an exception monitor to record the execution status and progress of the business method;
[0178] S403, monitoring runtime exceptions that occur during the execution of the business method in the try block, capturing the runtime exceptions through a catch structure, and switching to the exception handling logic;
[0179] S404, checking the return value of the business method. If the return value does not meet expectations, it is considered that an exception has occurred;
[0180] S405, processing the captured runtime exception, and recording detailed information of the runtime exception, including the time of occurrence, exception type, and code location;
[0181] S406: When an exception is detected, an exception flag is set to mark the execution status of the business method as abnormal.
[0182] In this embodiment, the try-catch structure is the basis of exception handling, allowing the system to capture and handle exceptions during the execution of business methods at runtime. In the scenario of multi-database transaction management, putting the business method in a try-catch structure ensures that any errors or exceptions are captured during the transaction operation, and performs corresponding transaction rollback or other recovery operations according to the exception situation.
[0183] In the calling code of the business method, use the try-catch structure to encapsulate the business logic to ensure that any exceptions can be caught during the execution of the method. Execute the actual business logic in the try block and handle the exception in the catch block to ensure that the system can correctly handle transactions according to the exception situation.
[0184] The exception monitor is a mechanism for tracking the execution status of business methods. Before the business method is executed, initializing the exception monitor can help the system record the execution process, key steps, and whether an exception occurs. The monitor can record information such as transaction processing time and operation status. Before the business method is executed, the exception monitor initialization code is called to pass the status information of the business method to the monitor. The monitor records the execution progress, call status, and any potential abnormal status of the method in real time.
[0185] Monitor the execution of business methods in the try block to ensure that the system can detect runtime exceptions such as RuntimeException immediately during execution. The catch block is responsible for catching these exceptions and entering the exception handling logic to ensure that transaction rollback or other recovery mechanisms can be executed correctly. Execute the core business logic in the try block of the business method and trigger the exception handling logic of the catch block when an exception occurs. Use a custom exception handler to record exception information and ensure that the transaction processing status is adjusted according to the exception.
[0186] When the business method is successfully executed, the system also needs to check the return value of the method. If the return value does not meet expectations, it may also be regarded as a logical error. The system should handle these return values that do not meet expectations to ensure the consistency of data operations. After the business method returns, the return value is judged. If the return value is null or does not meet expectations, the exception handling logic is entered. The transaction status is judged based on the return value, and a rollback operation is performed if necessary.
[0187] When an exception occurs, the system not only needs to handle the exception, but also needs to record detailed exception information for subsequent analysis. The recorded exception information includes the time, exception type, and the code location where the exception occurred. This information can help developers track the source of the problem and improve the transaction management mechanism of the system. In the catch block, the exception information is recorded through the log system, including the exception type, occurrence time, and code location. The exception information can be passed to the monitoring system for more advanced analysis and early warning processing.
[0188] When an exception occurs, the system needs to set a flag to mark that an exception has occurred in the current transaction or business operation. This flag can be used in subsequent transaction processing logic to ensure that the system can check the flag after the transaction is executed and decide whether to commit or roll back the transaction. In the catch block, set the exception flag to true to indicate that the business operation has an exception. Before the transaction is committed, check the status of the exception flag. If it is true, the transaction rollback is triggered.
[0189] This embodiment can ensure the consistency of transactions in a multi-database transaction environment by performing real-time monitoring when executing business methods and capturing possible exceptions. Whether it is a runtime exception or an unexpected return value, the system can detect and handle it in a timely manner. Combined with the exception handling mechanism and transaction rollback function, the system can ensure the security and consistency of data in abnormal situations, avoiding data inconsistency or fund loss caused by business failure or exceptions.
[0190] In one embodiment, in the above S50, extracting the transaction manager and transaction object from the ThreadLocal variable, and performing a commit operation on each transaction in turn, includes:
[0191] S501, extracting the transaction manager and transaction object from the ThreadLocal variable of the current thread by calling the ThreadLocal.get method;
[0192] S502, traversing all the extracted transaction managers and transaction objects in sequence, and processing each transaction one by one;
[0193] S503, before committing the transaction, check the status of each transaction object to confirm that it is in a committable state;
[0194] S504, calling the commit method of each transaction manager to commit the transaction of the corresponding database;
[0195] S505, when the submission is completed, call the ThreadLocal.remove method to clear the transaction manager and transaction object in the current thread.
[0196] In this embodiment, ThreadLocal is used to store data locally in the thread, ensuring that each thread has an independent transaction manager and transaction object. After the business method is executed, the system needs to extract the stored transaction manager and transaction object from ThreadLocal for transaction commit or rollback operations. By calling the ThreadLocal.get() method, the system obtains the previously stored transaction manager and transaction object from the current thread. These managers and objects are created and stored in ThreadLocal when the business method is executed, ensuring that each thread manages its transactions independently.
[0197] In a multi-database scenario, each database has an independent transaction manager and transaction object. Before committing a transaction, the system needs to traverse these managers and objects one by one to ensure that transactions of all databases can be processed correctly. Use a loop structure to traverse all transaction managers and transaction objects extracted from ThreadLocal. Process each extracted transaction manager and transaction object and prepare to perform a commit operation.
[0198] Before committing a transaction, the system must check the status of each transaction object to ensure that it is in a committable state. The status of a transaction object includes active state, rolled back state, etc. Only transactions in an active state can be committed. Call the getStatus() method of each transaction object to check the current status of the transaction. Only when the transaction is confirmed to be in an active state can the commit process be entered; if the transaction status is abnormal or has been rolled back, the commit operation is skipped.
[0199] The commit operation will make the changes in the database persistent. The system ensures that the transactions of multiple databases are successfully committed and the data is officially written to the database by calling the commit() method of each transaction manager. Call the commit() method of the transaction manager to commit the database transaction associated with the transaction manager. Ensure that all transaction managers commit the transactions they are responsible for one by one.
[0200] Once the transaction is committed or rolled back, the transaction manager and transaction object in ThreadLocal are no longer needed. Calling ThreadLocal.remove() method can clear the transaction data in the current thread to prevent data pollution and resource leakage. Calling ThreadLocal.remove() method removes the transaction manager and transaction object from the current thread, freeing up resources and preventing data confusion between threads.
[0201] In this embodiment, by extracting the transaction manager and transaction object from ThreadLocal and performing the commit operation, the system can ensure the independence and consistency of transaction operations in a multi-database environment. The commit process of each transaction undergoes a status check to ensure the safe commit of all transactions and avoid data inconsistency. Calling ThreadLocal.remove() can effectively prevent resource leakage and data pollution, and improve the stability and maintainability of the system.
[0202] In one embodiment, in the above S60, the corresponding transaction manager and transaction object are extracted from the ThreadLocal variable, and rollback operations are performed one by one to roll back all transactions, including:
[0203] S601, extracting the transaction manager and transaction object from the ThreadLocal variable of the current thread by calling the ThreadLocal.get method;
[0204] S602, traversing all the extracted transaction managers and transaction objects in sequence, and processing the transactions of each database one by one;
[0205] S603, before executing the rollback operation, check the status of each transaction object to confirm that the transaction is active;
[0206] S604, calling the rollback method of each transaction manager to roll back the changes in the transaction and restore the database to the state at the beginning of the transaction;
[0207] S605, when the rollback operation is completed, call the ThreadLocal.remove method to clear the transaction manager and transaction object stored in the current thread.
[0208] In this embodiment, when each thread executes a transaction, the transaction manager and transaction object are stored in ThreadLocal to ensure that the transaction states between threads do not interfere with each other. When an exception occurs during the execution of a business method, the system needs to extract the stored transaction manager and transaction object from the current thread through the ThreadLocal.get() method to prepare for the rollback operation of each database. Use the ThreadLocal.get() method to extract the transaction manager and transaction object from the current thread. These transaction managers and objects are stored in ThreadLocal during the execution process to ensure that each thread handles its own transaction independently.
[0209] In a multi-database environment, each database has an independent transaction manager and transaction object. Before the rollback operation, the system needs to process the transaction manager and transaction object of each database in turn to ensure that the transaction operations of all databases can be rolled back. Use a loop structure to traverse all transaction managers and transaction objects extracted from ThreadLocal. Rollback each extracted transaction manager to ensure that the transaction status of each database can be restored to the state at the beginning of the transaction.
[0210] Before performing a rollback operation, the system must check the current state of each transaction object to confirm that it is active. If the transaction object has been committed or is inactive, the rollback operation will be skipped to ensure that only active transactions are rolled back. Call the getStatus() method of the transaction object to check its status. If the transaction object is active, enter the rollback operation process; if the transaction object has been committed or is invalid, skip the rollback operation of the transaction.
[0211] The rollback operation is designed to undo all changes made during a transaction and restore the database to the state at the beginning of the transaction. Calling the rollback() method of the transaction manager ensures that all uncommitted changes are undone to avoid data inconsistency. Call the rollback() method of each transaction manager to undo the transactions managed by the transaction manager. Ensure that all uncommitted transactions are rolled back and the database is restored to the state at the beginning of the transaction.
[0212] Once the rollback operation is completed, the transaction manager and transaction object stored in ThreadLocal are no longer needed. Calling ThreadLocal.remove() can clear the transaction data in the current thread to prevent data pollution and resource leakage. Calling ThreadLocal.remove() method removes the transaction manager and transaction object, frees up memory resources, and avoids data confusion between threads.
[0213] This embodiment extracts the transaction manager and transaction object from ThreadLocal and performs a rollback operation. The system can ensure that in a multi-database scenario, when a business method fails to execute, transactions in all databases can be consistently rolled back. This mechanism effectively prevents the occurrence of data inconsistency problems and ensures data consistency and integrity. At the same time, calling ThreadLocal.remove() can avoid resource leakage and data confusion, further improving the security and stability of the system.
[0214] In one embodiment, a multi-database transaction aspect management device is provided, and the multi-database transaction aspect management device corresponds one-to-one to the multi-database transaction aspect management method in the above embodiment. Figure 3 , Figure 3 This is a functional module diagram of a preferred embodiment of the multi-database transaction aspect management device of the present invention. Annotation detection module 10, aspect interception module 20, transaction initialization module 30, business execution and monitoring module 40, transaction submission module 50 and transaction rollback module 60. The functional modules are described in detail as follows:
[0215] An annotation detection module 10 is used to determine whether the business method contains annotations for multi-database transaction control when calling the business method;
[0216] Aspect interception module 20, used to intercept the execution of the business method using a transaction aspect manager if the business method contains annotations for multi-database transaction control;
[0217] A transaction initialization module 30, for generating a transaction manager and a transaction object for each database according to the multiple database names specified in the annotation, and storing the transaction manager and the transaction object in a ThreadLocal variable of the current thread;
[0218] The business execution and monitoring module 40 is used to execute the business method and monitor the execution status during the execution of the business method to detect whether an abnormality occurs;
[0219] A transaction commit module 50 is used to extract the transaction manager and transaction object from the ThreadLocal variable if the business method is successfully executed, and to perform a commit operation on each transaction in turn;
[0220] The transaction rollback module 60 is used to extract the corresponding transaction manager and transaction object from the ThreadLocal variable if an exception occurs during the execution of the business method, and to perform rollback operations one by one to roll back all transactions.
[0221] In one embodiment, the annotation detection module 10 is specifically used for:
[0222] When a business method is called, the reflection mechanism is used to obtain the metadata of the business method, which includes the method name, parameter type and annotation information;
[0223] Scan all annotation information of the business method to obtain a list of annotations marked on the business method;
[0224] By traversing the annotation list, using the isAnnotationPresent method to determine whether the business method contains annotations for multi-database transaction control;
[0225] If the business method is not marked with the annotation of multi-database transaction control, check whether the parent class or interface of the business method contains the annotation of multi-database transaction control.
[0226] In one embodiment, the section interception module 20 is specifically used to:
[0227] Using the transaction aspect manager, defining a pointcut for identifying multi-database transaction control annotations by configuring interception points;
[0228] Use expression language to set pointcuts to intercept business methods annotated with multiple database transaction control annotations;
[0229] Before the business method is executed, the aspect logic is started through pre-notification;
[0230] When a business method is called, the execution of the business method is intercepted through the defined pointcut;
[0231] When intercepting a business method, parse the multi-database transaction control annotations marked on the business method and extract the parameter information in the annotations;
[0232] After intercepting the business method, the predefined aspect operation is executed to initialize the transaction management operation based on the parameter information in the annotation;
[0233] The execution process of business methods is controlled through dynamic proxy, and the execution order is determined according to the logic of transaction management.
[0234] In one embodiment, the transaction initialization module 30 is specifically used to:
[0235] Get multi-database transaction control annotation instances on business methods through reflection mechanism;
[0236] Parse the database name field in the annotation instance and build a list containing multiple database names;
[0237] Traversing the list of multiple database names, processing each database one by one;
[0238] Call the DataSource in the Spring container to obtain the corresponding data source according to each database name;
[0239] Using the DataSource of each database, initialize the corresponding transaction manager;
[0240] Setting transaction attributes for each transaction manager, the transaction attributes including propagation behavior and isolation level;
[0241] Call the getTransaction method of the transaction manager to generate a transaction object for each database and record the start status of the transaction;
[0242] Store each database's transaction manager and corresponding transaction object in the current thread's ThreadLocal variable.
[0243] In one embodiment, the service execution and monitoring module 40 is specifically used to:
[0244] Put the business method into a try-catch structure;
[0245] Before executing the business method, initializing an exception monitor to record the execution status and progress of the business method;
[0246] Monitor runtime exceptions that occur during the execution of business methods in the try block, capture the runtime exceptions through the catch structure, and turn to the exception handling logic;
[0247] Check the return value of the business method. If the return value does not meet expectations, it is considered an exception.
[0248] Process captured runtime exceptions and record detailed information about runtime exceptions, including the time of occurrence, exception type, and code location;
[0249] When an exception is detected, the exception flag is set to mark the execution status of the business method as abnormal.
[0250] In one embodiment, the transaction submission module 50 is specifically configured to:
[0251] By calling the ThreadLocal.get method, the transaction manager and transaction object are extracted from the ThreadLocal variable of the current thread;
[0252] Traverse all the extracted transaction managers and transaction objects in turn, and process each transaction one by one;
[0253] Before committing a transaction, check the status of each transaction object to confirm that it is in a committable state;
[0254] Call the commit method of each transaction manager to commit the transaction of the corresponding database;
[0255] When the submission is completed, call the ThreadLocal.remove method to clear the transaction manager and transaction objects in the current thread.
[0256] In one embodiment, the transaction rollback module 60 is specifically used to:
[0257] By calling the ThreadLocal.get method, the transaction manager and transaction object are extracted from the ThreadLocal variable of the current thread;
[0258] Traverse all the extracted transaction managers and transaction objects in turn, and process the transactions of each database one by one;
[0259] Before performing a rollback operation, check the status of each transaction object to confirm that the transaction is active;
[0260] Call the rollback method of each transaction manager to roll back the changes in the transaction and restore the database to the state at the beginning of the transaction;
[0261] When the rollback operation is completed, call the ThreadLocal.remove method to clear the transaction manager and transaction objects stored in the current thread.
[0262] In one embodiment, a computer device is provided. The computer device may be a server, and its internal structure diagram may be as follows: Figure 4 As shown. The computer device includes a processor, a memory, a network interface and a database connected via a system bus. The processor of the computer device is used to provide computing and control capabilities. The memory of the computer device includes a non-volatile and / or volatile storage medium and an internal memory. The non-volatile storage medium stores an operating system, a computer program and a database. The internal memory provides an environment for the operation of the operating system and the computer program in the non-volatile storage medium. The network interface of the computer device is used to communicate with an external client via a network connection. When the computer program is executed by the processor, it implements the functions or steps of a multi-database transaction aspect management method on the server side.
[0263] In one embodiment, a computer device is provided. The computer device may be a client, and its internal structure diagram may be as follows: Figure 5 As shown. The computer device includes a processor, a memory, a network interface, a display screen and an input device connected through a system bus. Among them, the processor of the computer device is used to provide computing and control capabilities. The memory of the computer device includes a non-volatile storage medium and an internal memory. The non-volatile storage medium stores an operating system and a computer program. The internal memory provides an environment for the operation of the operating system and the computer program in the non-volatile storage medium. The network interface of the computer device is used to communicate with an external server through a network connection. When the computer program is executed by the processor, it implements the functions or steps of the client side of a multi-database transaction aspect management method
[0264] In one embodiment, a computer device is provided, including a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor implements the following steps when executing the computer program:
[0265] When calling a business method, determine whether the business method contains annotations for multi-database transaction control;
[0266] If the business method contains annotations for multi-database transaction control, use the transaction aspect manager to intercept the execution of the business method;
[0267] Generate a transaction manager and a transaction object for each database according to the multiple database names specified in the annotation, and store the transaction manager and the transaction object in the ThreadLocal variable of the current thread;
[0268] Execute the business method, and monitor the execution status during the execution of the business method to detect whether an abnormality occurs;
[0269] If the business method is successfully executed, the transaction manager and transaction object are extracted from the ThreadLocal variable, and a commit operation is performed on each transaction in turn;
[0270] If an exception occurs during the execution of the business method, the corresponding transaction manager and transaction object are extracted from the ThreadLocal variable, and the rollback operation is performed one by one to roll back all transactions.
[0271] In one embodiment, a computer readable storage medium is provided, on which a computer program is stored, and when the computer program is executed by a processor, the following steps are implemented:
[0272] When calling a business method, determine whether the business method contains annotations for multi-database transaction control;
[0273] If the business method contains annotations for multi-database transaction control, use the transaction aspect manager to intercept the execution of the business method;
[0274] Generate a transaction manager and a transaction object for each database according to the multiple database names specified in the annotation, and store the transaction manager and the transaction object in the ThreadLocal variable of the current thread;
[0275] Execute the business method, and monitor the execution status during the execution of the business method to detect whether an abnormality occurs;
[0276] If the business method is successfully executed, the transaction manager and transaction object are extracted from the ThreadLocal variable, and a commit operation is performed on each transaction in turn;
[0277] If an exception occurs during the execution of the business method, the corresponding transaction manager and transaction object are extracted from the ThreadLocal variable, and the rollback operation is performed one by one to roll back all transactions.
[0278] It should be noted that the above functions or steps that can be implemented by the computer-readable storage medium or computer device can refer to the relevant descriptions on the server side and the client side in the aforementioned method embodiment. To avoid repetition, they will not be described one by one here.
[0279] Those skilled in the art can understand that all or part of the processes in the above-mentioned embodiment methods can be completed by instructing the relevant hardware through a computer program, and the computer program can be stored in a non-volatile computer-readable storage medium. When the computer program is executed, it can include the processes of the embodiments of the above-mentioned methods. Among them, any reference to memory, storage, database or other media used in the embodiments provided in this application can include non-volatile and / or volatile memory. Non-volatile memory can include read-only memory (ROM), programmable ROM (PROM), electrically programmable ROM (EPROM), electrically erasable programmable ROM (EEPROM) or flash memory. Volatile memory can include random access memory (RAM) or external cache memory. As an illustration and not limitation, RAM is available in many forms, such as static RAM (SRAM), dynamic RAM (DRAM), synchronous DRAM (SDRAM), double data rate SDRAM (DDRSDRAM), enhanced SDRAM (ESDRAM), synchronous link (Synchlink) DRAM (SLDRAM), memory bus (Rambus) direct RAM (RDRAM), direct memory bus dynamic RAM (DRDRAM), and memory bus dynamic RAM (RDRAM).
[0280] Those skilled in the art can clearly understand that for the convenience and simplicity of description, only the division of the above-mentioned functional units and modules is used as an example. In actual applications, the above-mentioned functions can be distributed and completed by different functional units and modules as needed, that is, the internal structure of the device can be divided into different functional units or modules to complete all or part of the functions described above.
[0281] It should be noted that if software tools or components other than those of the Company appear in the embodiments of the present application, they are only used for illustration and do not represent actual use. The above-described embodiments are only used to illustrate the technical solutions of the present invention, rather than to limit them; although the present invention has been described in detail with reference to the above-mentioned embodiments, a person of ordinary skill in the art should understand that the technical solutions described in the above-mentioned embodiments can still be modified, or some of the technical features thereof can be replaced by equivalents; and these modifications or replacements do not deviate the essence of the corresponding technical solutions from the spirit and scope of the technical solutions of the embodiments of the present invention, and should all be included in the protection scope of the present invention.
Claims
1. A multi-database transaction aspect management method, characterized in that: The following steps are involved: When calling a business method, determine whether the business method contains annotations for multi-database transaction control; If the business method contains annotations for multi-database transaction control, use the transaction aspect manager to intercept the execution of the business method; Generate a transaction manager and a transaction object for each database according to the multiple database names specified in the annotation, and store the transaction manager and the transaction object in the ThreadLocal variable of the current thread; Execute the business method, and monitor the execution status during the execution of the business method to detect whether an abnormality occurs; If the business method is successfully executed, the transaction manager and transaction object are extracted from the ThreadLocal variable, and a commit operation is performed on each transaction in turn; If an exception occurs during the execution of the business method, the corresponding transaction manager and transaction object are extracted from the ThreadLocal variable, and the rollback operation is performed one by one to roll back all transactions.
2. The multi-database transaction aspect management method according to claim 1, characterized in that: When calling a business method, determine whether the business method contains annotations for multi-database transaction control, including: When a business method is called, the reflection mechanism is used to obtain the metadata of the business method, which includes the method name, parameter type and annotation information; Scan all annotation information of the business method to obtain a list of annotations marked on the business method; By traversing the annotation list, using the isAnnotationPresent method to determine whether the business method contains annotations for multi-database transaction control; If the business method is not marked with the annotation of multi-database transaction control, check whether the parent class or interface of the business method contains the annotation of multi-database transaction control.
3. The multi-database transaction aspect management method according to claim 1, characterized in that: If the business method contains annotations for multi-database transaction control, the transaction aspect manager is used to intercept the execution of the business method, including: Using the transaction aspect manager, defining a pointcut for identifying multi-database transaction control annotations by configuring interception points; Use expression language to set pointcuts to intercept business methods annotated with multiple database transaction control annotations; Before the business method is executed, the aspect logic is started through pre-notification; When a business method is called, the execution of the business method is intercepted through the defined pointcut; When intercepting a business method, parse the multi-database transaction control annotations marked on the business method and extract the parameter information in the annotations; After intercepting the business method, the predefined aspect operation is executed to initialize the transaction management operation based on the parameter information in the annotation; The execution process of business methods is controlled through dynamic proxy, and the execution order is determined according to the logic of transaction management.
4. The multi-database transaction aspect management method according to claim 1, characterized in that: According to the multiple database names specified in the annotation, a transaction manager and a transaction object are generated for each database respectively, and the transaction manager and the transaction object are stored in the ThreadLocal variable of the current thread, including: Get multi-database transaction control annotation instances on business methods through reflection mechanism; Parse the database name field in the annotation instance and build a list containing multiple database names; Traversing the list of multiple database names, processing each database one by one; Call the DataSource in the Spring container to obtain the corresponding data source according to each database name; Using the DataSource of each database, initialize the corresponding transaction manager; Setting transaction attributes for each transaction manager, the transaction attributes including propagation behavior and isolation level; Call the getTransaction method of the transaction manager to generate a transaction object for each database and record the start status of the transaction; Store each database's transaction manager and corresponding transaction object in the current thread's ThreadLocal variable.
5. The multi-database transaction aspect management method as described in claim 1, characterized in that: Executing the business method and monitoring the execution status during the execution of the business method to detect whether an abnormality occurs, including: Put the business method into a try-catch structure; Before executing the business method, initializing an exception monitor to record the execution status and progress of the business method; Monitor runtime exceptions that occur during the execution of business methods in the try block, capture the runtime exceptions through the catch structure, and turn to the exception handling logic; Check the return value of the business method. If the return value does not meet expectations, it is considered an exception. Process captured runtime exceptions and record detailed information about runtime exceptions, including the time of occurrence, exception type, and code location; When an exception is detected, the exception flag is set to mark the execution status of the business method as abnormal.
6. The multi-database transaction aspect management method according to claim 1, characterized in that: Extract the transaction manager and transaction object from the ThreadLocal variable, and perform a commit operation on each transaction in turn, including: By calling the ThreadLocal.get method, the transaction manager and transaction object are extracted from the ThreadLocal variable of the current thread; Traverse all the extracted transaction managers and transaction objects in turn, and process each transaction one by one; Before committing a transaction, check the status of each transaction object to confirm that it is in a committable state; Call the commit method of each transaction manager to commit the transaction of the corresponding database; When the submission is completed, call the ThreadLocal.remove method to clear the transaction manager and transaction objects in the current thread.
7. The multi-database transaction aspect management method according to claim 1, characterized in that: Extract the corresponding transaction manager and transaction object from the ThreadLocal variable, perform rollback operations one by one, and roll back all transactions, including: By calling the ThreadLocal.get method, the transaction manager and transaction object are extracted from the ThreadLocal variable of the current thread; Traverse all the extracted transaction managers and transaction objects in turn, and process the transactions of each database one by one; Before performing a rollback operation, check the status of each transaction object to confirm that the transaction is active; Call the rollback method of each transaction manager to roll back the changes in the transaction and restore the database to the state at the beginning of the transaction; When the rollback operation is completed, call the ThreadLocal.remove method to clear the transaction manager and transaction objects stored in the current thread.
8. A multi-database transaction aspect management device, characterized in that: The multi-database transaction aspect management device comprises: An annotation detection module is used to determine whether the business method contains annotations for multi-database transaction control when calling the business method; Aspect interception module, used to intercept the execution of the business method using the transaction aspect manager if the business method contains annotations for multi-database transaction control; A transaction initialization module, used to generate a transaction manager and a transaction object for each database according to the multiple database names specified in the annotation, and store the transaction manager and the transaction object in the ThreadLocal variable of the current thread; A business execution and monitoring module, used to execute the business method and monitor the execution status during the execution of the business method to detect whether an abnormality occurs; A transaction commit module, used to extract the transaction manager and transaction object from the ThreadLocal variable if the business method is successfully executed, and perform a commit operation on each transaction in turn; The transaction rollback module is used to extract the corresponding transaction manager and transaction object from the ThreadLocal variable if an exception occurs during the execution of the business method, and perform rollback operations one by one to roll back all transactions.
9. A computer device, characterized in that: The computer device includes a memory, a processor, and a multi-database transaction aspect management program stored in the memory and executable on the processor. When the multi-database transaction aspect management program is executed by the processor, the steps of the multi-database transaction aspect management method according to any one of claims 1 to 7 are implemented.
10. A computer-readable storage medium, characterized in that: The storage medium stores a multi-database transaction aspect management program, which, when executed by a processor, implements the steps of the multi-database transaction aspect management method according to any one of claims 1 to 7.
Citation Information
Cited By
Dynamic multi-data source switching assembly and implementation method thereof
CN119473436A
Method and system for managing visualization tables of databases of different types
CN119537424A
Transaction-based data resource management method and device, medium and electronic equipment
CN120085970A
Transaction-based Data Resource Management Method, Device, Medium, and Electronic Device
CN120085970B
