1、Seata是什么
Seata 是一款开源的分布式事务解决方案,致力于提供高性能和简单易用的分布式事务服务。Seata 将为用户提供了 AT、TCC、SAGA 和 XA 事务模式,为用户打造一站式的分布式解决方案。
2、seata控制分布式事务
1)、每一个微服务创建一个undo_log表;
CREATE TABLE `undo_log` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`branch_id` bigint(20) NOT NULL,
`xid` varchar(100) NOT NULL,
`context` varchar(128) NOT NULL,
`rollback_info` longblob NOT NULL,
`log_status` int(11) NOT NULL,
`log_created` datetime NOT NULL,
`log_modified` datetime NOT NULL,
`ext` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
2)、创建业务表
3)、安装事务协调器
seata-server https://github.com/seata/seata/releases
4)、整合springBoot
- 导入依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
<version>2022.0.0.0</version>
</dependency>
- 启动seata-server
本文中所使用seata-server2.0.0 版本 ,配置application.yml,注册进consul注册中心。若配置其他注册中心,可参考application.example.yml
server:
port: 7091
spring:
application:
name: seata-server
logging:
config: classpath:logback-spring.xml
file:
path: ${log.home:${user.home}/logs/seata}
extend:
logstash-appender:
destination: 127.0.0.1:4560
kafka-appender:
bootstrap-servers: 127.0.0.1:9092
topic: logback_to_logstash
console:
user:
username: seata
password: seata
seata:
config:
# support: nacos, consul, apollo, zk, etcd3
type: consul
consul:
server-addr: 127.0.0.1:8500
acl-token:
key: seata.properties
enable: true
registry:
# support: nacos, eureka, redis, zk, consul, etcd3, sofa
type: consul
consul:
cluster: default
server-addr: 127.0.0.1:8500
acl-token:
enable: true
store:
# support: file 、 db 、 redis 、 raft
mode: file
# server:
# service-port: 8091 #If not configured, the default is '${server.port} + 1000'
security:
secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017
tokenValidityInMilliseconds: 1800000
ignore:
urls: /,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.jpeg,/**/*.ico,/api/v1/auth/login,/metadata/v1/**
**注意:**seata.properties该文件必须配置,配置内容为 seata-server-2.0.0\seata\script\config-center\config.txt 内的文件内容
- springboot项目配置
server.port=9000
spring.application.name=seata-order
#====================================data source =============================================
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/shop?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
spring.datasource.username=
spring.datasource.password=
logging.level.com.example.order=debug
#====================================mybatis config==========================================
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.mapper-locations=classpath*:/mapper/*.xml
#====================================Seata Config=============================================
seata.registry.type=consul
seata.registry.consul.server-addr=localhost:8500
#事务分组配置
seata.tx-service-group=default_tx_group # 1.5版本版本之后改为default_tx_group 之前为my_test_tx_group
seata.service.vgroup-mapping.default_tx_group=default # 注意:必须要与 seata-server 中配置的 cluster 一致
seata.service.grouplist.default=127.0.0.1:8091
- 注入 DataSourceProxy
因为 Seata 通过代理数据源实现分支事务,如果没有注入,事务无法成功回滚。
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DruidDataSource druidDataSource() {
return new DruidDataSource();
}
/**
* 需要将 DataSourceProxy 设置为主数据源,否则事务无法回滚
*
* @param druidDataSource The DruidDataSource
* @return The default datasource
*/
@Primary
@Bean("dataSource")
public DataSource dataSource(DruidDataSource druidDataSource) {
return new DataSourceProxy(druidDataSource);
}
- 接口使用
@GlobalTransactional
添加注解,控制全局事务。
示例:
@Resource
TestDao testDao;
@Resource
InventoryServiceClient inventoryServiceClient;
@Override
@Transactional
@GlobalTransactional
public void getList(Order order) {
testDao.insertOrder(order);
Inventory inventory = new Inventory();
inventory.setPoId(order.getPoId());
inventory.setNum(order.getQty());
// 远程调用
inventoryServiceClient.insertInventory(inventory);
int a = 9 / 0;
System.out.println(a);
}
@GlobalTransactional 不适用于高并发情况。