当前位置:网站首页>Xa mode explanation and code implementation of four Seata modes
Xa mode explanation and code implementation of four Seata modes
2022-06-23 05:28:00 【In a flash】
Catalog
1、 Implementation mechanism
Realization XA Pattern , Need to support XA Transaction database
AT The pattern is Seata Default mode , Meet the two-phase submission agreement :
- A stage ( Execution phase ):XA Start + perform SQL( The transaction will not be committed )+XA End, Register branch transactions ;XA prepare, Ensure branch status .
- Two stages ( Completion stage ):
- Submit : perform XA The branch commit.
- Roll back : perform XA The branch rollback.

2、 Advantages and disadvantages
- advantage :
- XA In mode , All transactions will wait for each other , achieve Strong consistency The effect of .
- shortcoming :
- It will occupy the database lock , Waste of resources , Performance degradation , It needs the support of the database itself XA.
3、 Code implementation
Create two SpringBoot engineering , Respectively storage-service And order-service, Simulation from on order-service New orders in the service , And then call storage-service Service new inventory deduction record ; The core code is as follows , Refer to the end of the text for the complete code github Address ;
In coding mode ,XA Pattern And AT Pattern bring into correspondence with , You only need to change the data source proxy configuration to XA that will do , Revised as follows :
seata:
data-source-proxy-mode: XA
3.1 Create table statement
-- Database name : seata-xa-demo.sql
-- The order sheet
CREATE TABLE `tb_order`
(
`id` int(11) NOT NULL COMMENT ' Primary key ',
`count` int(11) NULL DEFAULT 0 COMMENT ' Order quantity ',
`money` int(11) NULL DEFAULT 0 COMMENT ' amount of money ',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = COMPACT;
-- An inventory statement
CREATE TABLE `tb_storage`
(
`id` int(11) NOT NULL COMMENT ' Primary key ',
`order_id` int(11) NOT NULL COMMENT ' Order ID',
`count` int(11) NOT NULL DEFAULT 0 COMMENT ' stock ',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = COMPACT;
Be careful : If you use a higher version of mysql The drive may appear com.mysql.cj.conf.PropertySet.getBooleanReadableProperty(java.lang.String) abnormal , Need to put mysql Version back to 8.0.11 edition ;
3.2 order-service service
3.2.1 yaml To configure
server:
port: 8082
spring:
application:
name: order-service
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3307/seata-at-demo?useUnicode=true&useSSL=false&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=Asia/Shanghai
username: root
password: lhzlx
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
namespace: 64ed9ca7-d705-4655-b4e4-f824e420a12a
group: test
seata:
enabled: true
# Use XA Pattern
data-source-proxy-mode: XA
application-id: ${
spring.application.name}
# The name of the transaction group , Corresponding service.vgroupMapping.default_tx_group=xxx Configured in default_tx_group
tx-service-group: default_tx_group
# Configure the correspondence between the transaction group and the cluster
service:
vgroup-mapping:
# default_tx_group Is the name of the transaction Group ,default Name the cluster
default_tx_group: default
disable-global-transaction: false
registry:
type: nacos
nacos:
application: seata-server
server-addr: 127.0.0.1:8848
group: SEATA_GROUP
namespace: 64ed9ca7-d705-4655-b4e4-f824e420a12a
username: nacos
password: nacos
cluster: default
config:
type: nacos
nacos:
server-addr: 162.14.115.18:8848
group: SEATA_GROUP
namespace: 64ed9ca7-d705-4655-b4e4-f824e420a12a
username: nacos
password: nacos
data-id: seataServer.properties
3.2.2 Service
Upstream services through @GlobalTransactional Annotations enable global transactions , Use storageClient Conduct feign call
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
@Resource
private StorageClient storageClient;
@Resource
private OrderMapper orderMapper;
/** * Create order * * @param order * @return */
@Override
@GlobalTransactional
public Long create(Order order) {
// Create order
long id = new Random().nextInt(999999999);
order.setId(id);
orderMapper.insert(order);
try {
// Record inventory information
storageClient.deduct(order.getId(), order.getCount());
// Simulate anomalies
// int a = 1 / 0;
} catch (FeignException e) {
log.error(" Order failure , reason :{}", e.contentUTF8(), e);
throw new RuntimeException(e.contentUTF8(), e);
}
return order.getId();
}
}
3.2.3 StorageClient
@FeignClient("storage-service")
public interface StorageClient {
/** * Deducting the inventory * * @param orderId * @param count */
@PostMapping("/storage")
void deduct(@RequestParam("orderId") Long orderId, @RequestParam("count") Integer count);
}
3.3 storage-service service
3.3.1 yaml To configure
server:
port: 8081
spring:
application:
name: storage-service
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3307/seata-xa-demo?useUnicode=true&useSSL=false&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=Asia/Shanghai
username: root
password: lhzlx
cloud:
nacos:
discovery:
server-addr: 162.14.115.18:8848
namespace: 64ed9ca7-d705-4655-b4e4-f824e420a12a
group: test
# stay dev Environment debug when , You can set the time to be longer
#heart-beat-interval: 1000 # Heartbeat interval . The unit is millisecond , Default 5*1000
heart-beat-timeout: 300000 # Cardiac arrest , No heartbeat , Will set the instance as unhealthy . The unit is millisecond , Default 15*1000
ip-delete-timeout: 4000000 #Ip Delete timeout , No heartbeat , The instance will be deleted . The unit is millisecond , Default 30*1000
seata:
enabled: true
# Turn on XA Pattern
data-source-proxy-mode: XA
application-id: ${
spring.application.name}
# The name of the transaction group , Corresponding service.vgroupMapping.default_tx_group=xxx Configured in default_tx_group
tx-service-group: default_tx_group
# Configure the correspondence between the transaction group and the cluster
service:
vgroup-mapping:
# default_tx_group Is the name of the transaction Group ,default Name the cluster
default_tx_group: default
disable-global-transaction: false
registry:
type: nacos
nacos:
application: seata-server
server-addr: 127.0.0.1:8848
group: SEATA_GROUP
namespace: 64ed9ca7-d705-4655-b4e4-f824e420a12a
username: nacos
password: nacos
cluster: default
config:
type: nacos
nacos:
server-addr: 162.14.115.18:8848
group: SEATA_GROUP
namespace: 64ed9ca7-d705-4655-b4e4-f824e420a12a
username: nacos
password: nacos
data-id: seataServer.properties
3.3.2 StorageService
@Slf4j
@Service
public class StorageServiceImpl implements StorageService {
@Resource
private StorageMapper storageMapper;
/** * Deduct the amount of storage * * @param orderId * @param count */
@Override
public void deduct(Long orderId, int count) {
log.info(" Start recording inventory information ");
try {
long id = new Random().nextInt(999999999);
Storage storage = new Storage();
storage.setId(id);
storage.setOrderId(orderId);
storage.setCount(count);
storageMapper.insert(storage);
// Simulate anomalies
// int a = 1 / 0;
} catch (Exception e) {
throw new RuntimeException(" Inventory deduction failed , It may be that the inventory is insufficient !", e);
}
log.info(" Inventory information recorded successfully ");
}
}
3.4 test
There is no screenshot for demonstration during the test , It only shows the result , You can run code to set exceptions to verify
3.4.1 Downstream service is abnormal
stay order-service The service is normal , stay storage-service Service service Exception thrown in , Observe whether the data is successfully rolled back ; If tb_order And tb_storage There is no data , Indicates that the global transaction is successful ;
3.4.2 The upstream service is abnormal
order-service The service is executing storageClient.deduct() Method to throw an exception , stay storage-service The service is normal , Observe whether the data is successfully rolled back ; If tb_order And tb_storage There is no data , Indicates that the global transaction is successful ;
3.4.3 Strong data consistency verification
XA Patterns and AT The pattern differs in ,XA Is strongly consistent and AT It's ultimate consistency ;
We can complete the upstream service orderMapper.insert(order); Enter the breakpoint immediately after , The test will find that tb_order No data in , Re release breakpoints enable normal program execution , If you look at the database again, you will find tb_order There's data in , It means that strong consistency of data is achieved instead of final consistency ;
4、 Source code address
Seata value AT Pattern code implementation :《seata-xa-demo》
边栏推荐
- 戏问花门酒家翁
- Baidu PaddlePaddle's "universal gravitation" first stop in 2022 landed in Suzhou, comprehensively launching the SME empowerment plan
- 渗透测试基础 | 附带测试点、测试场景
- 今日睡眠质量记录80分
- 618 how to break through the siege? Haier Zhijia: do a good job in digitalization of users
- JDBC入门学习(一)之DML操作
- MCS: discrete random variable Bernoulli distribution
- 弱者易怒如虎,强者平静如水,真正厉害的人早已戒掉了情绪
- How to conduct exploratory data analysis
- C language stack implementation
猜你喜欢
随机推荐
第九章 APP项目测试(1)
JDBC入门学习(一)之DML操作
JDBC introductory learning (II) encapsulation tool class
Mmdeploy quick installation and instructions
面对新的挑战,成为更好的自己--进击的技术er
数学分析_笔记_第1章:集合与映射
Array The from method creates an undefined array of length n
MySQL自定义序列数的实现
CF【1700D】D. River Locks(dp、二分、数学)
MCS: discrete random variable - uniform distribution
618 how to break through the siege? Haier Zhijia: do a good job in digitalization of users
Missing essential plugin
The propeller framework v2.3 releases the highly reusable operator library Phi! Restructure development paradigm to reduce cost and increase efficiency
99 multiplication table bat
Chapter IX app project test (1)
PHP move_ uploaded_ File failed to upload mobile pictures
JDBC入门学习(二)之封装工具类
MCS: continuous random variable - student's t distribution
Introduction to JDBC (III) implementation of transaction rollback function
The tiobe programming language ranking is an indicator of the popular trend of programming languages









![[leetcode] longest increasing subsequence problem and its application](/img/e0/d666dccec1f65eed61fce83ac2190a.png)