Table of Contents
1. What is a distributed transaction?
2. Reasons for distributed transactions
2.1. Database sub-database and sub-table
2.2. Application of SOA
3. ACID characteristics of transactions
3.1. Atomicity (A)
3.2. Consistency (C)
3.3. Isolation (I)
3.4. Durability (D)
4. Application scenarios of distributed transactions
4.1. Payment
4.2. Online ordering
5. Common distributed transaction solutions
5.1. Two-phase submission based on XA protocol
5.2, Message Transaction + Final Consistency
5.3. TCC Programming Mode
6. Summary
Home Java javaTutorial In-depth understanding of JAVA distributed transactions

In-depth understanding of JAVA distributed transactions

Apr 03, 2018 pm 02:33 PM
java affairs distributed

This article mainly introduces an in-depth understanding of JAVA distributed transactions. The editor thinks it is quite good. Now I will share it with you and give you a reference. Let’s follow the editor and take a look.

1. What is a distributed transaction?

Distributed transaction refers to the participants of the transaction, the server that supports the transaction, and the resource server. and transaction managers are located on different nodes in different distributed systems. The above is the explanation from Baidu Encyclopedia. Simply put, a large operation is composed of different small operations. These small operations are distributed on different servers and belong to different applications. Distributed transactions need to ensure that these small operations are either all Succeed or fail all. Essentially, distributed transactions are to ensure data consistency in different databases.

2. Reasons for distributed transactions

2.1. Database sub-database and sub-table

When the data generated by a single database table in a year exceeds 1000W, then we need to consider database and table sharding. The specific principles of database and table sharding will not be explained here. I will go into details later when I have time. To put it simply, the original one database has become multiple databases. At this time, if an operation accesses both the 01 library and the 02 library, and the consistency of the data must be ensured, then distributed transactions must be used.

2.2. Application of SOA

The so-called SOA is the service-oriented business. For example, a single machine originally supported the entire e-commerce website, but now the entire website has been dismantled and separated into the order center, user center, and inventory center. For the order center, there is a special database to store order information, the user center also has a special database to store user information, and the inventory center also has a special database to store inventory information. At this time, if you want to operate orders and inventory at the same time, it will involve the order database and inventory database. In order to ensure data consistency, distributed transactions need to be used.

The above two situations have different appearances, but the essence is the same, both because there are more databases to operate!

3. ACID characteristics of transactions

3.1. Atomicity (A)

The so-called atomicity means that all operations in the entire transaction are either completed, Either do nothing, there is no in-between. If an error occurs during transaction execution, all operations will be rolled back, and the entire transaction will be as if it had never been executed.

3.2. Consistency (C)

The execution of transactions must ensure the consistency of the system. Take transfer as an example. A has 500 yuan and B has 300 yuan. , if A successfully transfers 50 yuan to B in a transaction, then no matter how many concurrencies there are, no matter what happens, as long as the transaction is executed successfully, then in the end, account A must be 450 yuan, and account B must be 350 yuan.

3.3. Isolation (I)

The so-called isolation means that transactions will not affect each other, and the intermediate state of a transaction will not be Other transaction awareness.

3.4. Durability (D)

The so-called persistence means that after a single transaction is completed, the changes made to the data by the transaction will be completely saved in stored in the database, even if a power outage occurs or the system is down.

4. Application scenarios of distributed transactions

4.1. Payment

The most classic scenario is payment. A payment is a payment for a purchase. To deduct money from the home account and add money to the seller's account at the same time, these operations must be performed in one transaction, either all of them succeed or all of them fail. As for the buyer's account, which belongs to the buyer center, it corresponds to the buyer's database, while the seller's account belongs to the seller's center, which corresponds to the seller's database. Operations on different databases must introduce distributed transactions.

4.2. Online ordering

Buyers placing orders on e-commerce platforms often involve two actions, one is to deduct inventory, and the second is to update Order status, inventory and orders generally belong to different databases, and distributed transactions need to be used to ensure data consistency.

5. Common distributed transaction solutions

5.1. Two-phase submission based on XA protocol

XA is a distributed transaction protocol proposed by Tuxedo. XA is roughly divided into two parts: transaction manager and local resource manager. The local resource manager is often implemented by a database. Commercial databases such as Oracle and DB2 all implement the XA interface, and the transaction manager serves as the global scheduler and is responsible for the submission and rollback of each local resource. The principle of XA implementing distributed transactions is as follows:

Generally speaking, the XA protocol is relatively simple, and once a commercial database implements the XA protocol, use The cost of distributed transactions is also relatively low. However, XA also has a fatal shortcoming, that is, its performance is not ideal. Especially in the transaction order link, the amount of concurrency is often very high, and XA cannot meet high concurrency scenarios. XA is currently supported ideally in commercial databases, but not so well in mysql databases. The XA implementation of mysql does not record prepare phase logs, and switching back between the active and standby databases results in data inconsistency between the active and standby databases. Many nosql also do not support XA, which makes the application scenarios of XA very narrow.

5.2, Message Transaction + Final Consistency

The so-called message transaction is a two-stage submission based on message middleware, which is essentially a kind of message middleware. Special utilization, it puts local transactions and message sending in a distributed transaction, ensuring that either the local operation succeeds and the external message is sent successfully, or both fail. The open source RocketMQ supports this feature. The specific principle is as follows :

1, System A sends a preliminary message to the message middleware
2, The message middleware saves the preliminary message and returns success
3. A executes a local transaction
4. A sends a commit message to the message middleware

A message transaction is completed through the above 4 steps. For the above 4 steps, each step may cause errors. Let’s analyze them one by one:

  • If an error occurs in step one, the entire transaction will fail and will not be executed. A’s local operation

  • If an error occurs in step two, the entire transaction will fail and A’s local operation will not be executed

  • An error occurred in step three. At this time, the preparation message needs to be rolled back. How to roll back? The answer is that system A implements a callback interface for message middleware. The message middleware will continuously execute the callback interface to check whether transaction A is executed successfully. If it fails, the prepared message will be rolled back

  • There is an error in step 4. At this time, A's local transaction is successful. Does the message middleware need to roll back A? The answer is no. In fact, through the callback interface, the message middleware can check that A has executed successfully. At this time, there is actually no need for A to send a submission message. The message middleware can submit the message by itself, thereby completing the entire message transaction

Two-phase commit based on message middleware is often used in high concurrency scenarios to split a distributed transaction into a message transaction (local operation of system A + message sending ) + local operation of system B. The operation of system B is driven by messages. As long as the message transaction is successful, the operation of A must be successful and the message must be sent. At this time, B will receive the message to perform the local operation. If the local operation If it fails, the message will be re-delivered until the operation of B is successful, thus realizing the distributed transaction of A and B in disguise. The principle is as follows:

Although the above solution can complete the operations of A and B, A and B are not strictly consistent, but ultimately consistent. Yes, we sacrificed consistency here in exchange for a substantial improvement in performance. Of course, this kind of gameplay is also risky. If B continues to fail to execute, the consistency will be destroyed. Whether to play it depends on how much risk the business can bear.

5.3. TCC Programming Mode

The so-called TCC programming mode is also a variant of two-phase submission. TCC provides a programming framework that divides the entire business logic into three parts: Try, Confirm and Cancel operations. Taking online ordering as an example, the Try stage will deduct inventory, and the Confirm stage will update the order status. If the order update fails, it will enter the Cancel stage and the inventory will be restored. In short, TCC artificially implements two-stage submission through code. The codes written in different business scenarios are different and the complexity is also different. Therefore, this model cannot be reused well.

6. Summary

Distributed transactions are essentially unified control of transactions in multiple databases. According to the control intensity, they can be divided into: no control and partial control. and complete control. No control means not introducing distributed transactions. Partial control means two-phase commit of various variants, including the message transaction + eventual consistency and TCC mode mentioned above. Full control means fully realizing two-phase commit. The advantage of partial control is that concurrency and performance are very good. The disadvantage is that data consistency is weakened. Full control sacrifices performance and ensures consistency. Which method to use ultimately depends on the business scenario. As a technician, you must not forget that technology serves the business. Do not use technology for the sake of technology. Technology selection for different businesses is also a very important ability!

The above is the detailed content of In-depth understanding of JAVA distributed transactions. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1230
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles