115、商城业务---分布式事务---使用Springboot提供的Seata解决分布式事务

https://seata.io/zh-cn/

seata使用Seata AT模式控制分布式事务的步骤:
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、下载并安装事务协调器seata-server
https://github.com/seata/seata/releases

3、整合
(1)导入依赖注意只要在需要seata的服务中导入,因为如果在不需要seata的服务中导入,这个服务中又没有相应的seata配置,就会报错导致服务无法启动

       <!--引入管理分布式事务的seata-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
        </dependency>

springcloud版本是Greenwich.SR3,springboot版本是2.1.8.RELEASE引入的seata-all的版本是0.7.1
所以下载seata-server版本是0.7.1
(2)、安装seata-server0.7.1版本
首先修改seata-server中的配置,将他加入我们的nacos注册中心管理

(3)使用seata只需要使用注解@GlobalTransactional标在方法上

(4)所有想要使用分布式事务的微服务都要使用seata DataSourceProxy代理自己的数据源

package com.gulimall.order.config;

import com.zaxxer.hikari.HikariDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;

/**
 * 使用seata DataSourceProxy代理自己的数据源
 */
@Configuration
public class MySeataConfig {

    @Autowired
    DataSourceProperties dataSourceProperties;


    @Bean
    public DataSource dataSource(DataSourceProperties dataSourceProperties) {

        HikariDataSource dataSource = dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
        if (StringUtils.hasText(dataSourceProperties.getName())) {
            dataSource.setPoolName(dataSourceProperties.getName());
        }

        return new DataSourceProxy(dataSource);
    }

}

(5)每个微服务都必须导入registry.conf、file.conf
这两个文件都在我们的下载的seata-server文件夹中。
同时修改file.conf中的下面位置

即修改成vgroup_mapping.项目名-fescar-service-group = "default"
(6)给分布式大事务的入口标注@GlobalTransactional
(7)给大事务中调用的远程方法上只需要标注@Transactional即可
4、进行测试,发现如果一个服务发生异常回滚,则它方法中调用的远程事务也会回滚

posted @ 2023-02-23 16:46  不是孩子了  阅读(69)  评论(0)    收藏  举报