1.启动Seata Server端,Seata Server使用nacos作为配置中心和注册中心
参考:Seata服务搭建 —— nacos
2.配置微服务整合seata
第一步:添加maven依赖
<!-- seata --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-seata</artifactId> </dependency>
第二步:各微服务对应数据库中添加undo_log表
CREATE TABLE `undo_log` ( `branch_id` bigint(20) NOT NULL COMMENT 'branch transaction id', `xid` varchar(100) NOT NULL COMMENT 'global transaction id', `context` varchar(128) NOT NULL COMMENT 'undo_log context,such as serialization', `rollback_info` longblob NOT NULL COMMENT 'rollback info', `log_status` int(11) NOT NULL COMMENT '0:normal status,1:defense status', `log_created` datetime(6) NOT NULL COMMENT 'create datetime', `log_modified` datetime(6) NOT NULL COMMENT 'modify datetime', UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='AT transaction mode undo table';
第三步:配置事务分组
server: port: 8072 # 数据库 spring: datasource: username: root password: root url: jdbc:mysql://106.14.156.185:3306/seata_stock?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource # 初始化时运行sql脚本 # schema: # - classpath:sql/schema.sql #initialization-mode: never application: name: alibaba-stock-seata cloud: nacos: server-addr: 127.0.0.1:8848 username: nacos password: nacos alibaba: seata: tx-service-group: default_tx_group # 配置事务分组 # 设置mybatis mybatis: mapper-locations: classpath*:mapper/*.xml type-aliases-package: com.mry.seata.mapper configuration: cache-enabled: true lazy-loading-enabled: true multiple-result-sets-enabled: true use-column-label: true default-executor-type: reuse default-statement-timeout: 25000
第四步:配置seata
seata: registry: # 配置seata的注册中心, 告诉seata server 这么去访问seata server(TC) type: nacos nacos: server-addr: 127.0.0.1:8848 # seata server 所在的nacos服务地址 application: seata-server # seata server 的服务名为seata-server, 如果没有修改可以不配 username: nacos password: nacos group: SEATA_GROUP # seata server 所在的组,默认就是SEATA_GROUP, 没有修改也可以不配 config: # 配置seata的配置中心, 可以读取关于seata client的一些配置 type: nacos nacos: server-addr: 127.0.0.1:8848 username: nacos password: nacos group: SEATA_GROUP
第五步:开启分布式事务 @GlobalTransactional
@Service public class OrderServiceImpl implements OrderService { @Autowired OrderMapper orderMapper; @Autowired StockService stockService; /** * 下单 * @param order */ @GlobalTransactional @Override public Order create(Order order) { //插入能否成功 orderMapper.insert(order); stockService.reduct(order.getProductId()); //异常 int a = 1/0; return order; } }