Seata的搭建及使用

  • Post author:
  • Post category:其他


官方文档:http://seata.io/zh-cn/docs/user/quickstart.html



架构图:

有三个服务分别为订单服务、库存服务、账户服务

主要业务逻辑为采购业务,进行采购时需要进行下订单、账号登记、减库存等操作!

在这里插入图片描述

TC:事务协调者,也就是seata的服务端

TM:事务管理者,也就是案例中的采购业务

RM:资源管理者,案例中的订单服务、库存服务、账户服务




服务端配置


1)建库建表。以mysql数据库为例。

全局事务会话信息,以

全局事务



分支事务



全局锁

三部分构成,对应表

global_table



branch_table



lock_table

在下载的安装包README文件中提供了存放脚本的位置

https://github.com/seata/seata/blob/develop/script/server/db/mysql.sql

在这里插入图片描述

-- -------------------------------- The script used when storeMode is 'db' --------------------------------
-- the table to store GlobalSession data
CREATE TABLE IF NOT EXISTS `global_table`
(
    `xid`                       VARCHAR(128) NOT NULL,
    `transaction_id`            BIGINT,
    `status`                    TINYINT      NOT NULL,
    `application_id`            VARCHAR(32),
    `transaction_service_group` VARCHAR(32),
    `transaction_name`          VARCHAR(128),
    `timeout`                   INT,
    `begin_time`                BIGINT,
    `application_data`          VARCHAR(2000),
    `gmt_create`                DATETIME,
    `gmt_modified`              DATETIME,
    PRIMARY KEY (`xid`),
    KEY `idx_gmt_modified_status` (`gmt_modified`, `status`),
    KEY `idx_transaction_id` (`transaction_id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

-- the table to store BranchSession data
CREATE TABLE IF NOT EXISTS `branch_table`
(
    `branch_id`         BIGINT       NOT NULL,
    `xid`               VARCHAR(128) NOT NULL,
    `transaction_id`    BIGINT,
    `resource_group_id` VARCHAR(32),
    `resource_id`       VARCHAR(256),
    `branch_type`       VARCHAR(8),
    `status`            TINYINT,
    `client_id`         VARCHAR(64),
    `application_data`  VARCHAR(2000),
    `gmt_create`        DATETIME(6),
    `gmt_modified`      DATETIME(6),
    PRIMARY KEY (`branch_id`),
    KEY `idx_xid` (`xid`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

-- the table to store lock data
CREATE TABLE IF NOT EXISTS `lock_table`
(
    `row_key`        VARCHAR(128) NOT NULL,
    `xid`            VARCHAR(96),
    `transaction_id` BIGINT,
    `branch_id`      BIGINT       NOT NULL,
    `resource_id`    VARCHAR(256),
    `table_name`     VARCHAR(32),
    `pk`             VARCHAR(36),
    `gmt_create`     DATETIME,
    `gmt_modified`   DATETIME,
    PRIMARY KEY (`row_key`),
    KEY `idx_branch_id` (`branch_id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;


2) 修改服务端配置文件


2.1 file.conf

store {
  ## store mode: file、db  数据源配置
  mode = "db"
  ## database store property
  db {
    datasource = "druid"
    ## mysql/oracle/postgresql/h2/oceanbase etc.
    dbType = "mysql"
    driverClassName = "com.mysql.jdbc.Driver"
    url = "jdbc:mysql://127.0.0.1:3306/seata"
    user = "mysql"
    password = "mysql"
    minConn = 5
    maxConn = 30
    globalTable = "global_table"
    branchTable = "branch_table"
    lockTable = "lock_table"
    queryLimit = 100
    maxWait = 5000
  }
}


注意

:如果使用nacos为注册中心file.conf文件内容可以放到配置中心中实现动态刷新;

如果不使用注册中心,registry.conf type设置为file,则registry.conf,file.conf需要copy到每个服务中


2.2 registry.conf

registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "nacos"  #seata服务的注册类型,这里是nacos,所以对应配置的是nacos相关信息

  nacos {
    application = "seata-server"
    serverAddr = "127.0.0.1:8848"
    group = "SEATA_GROUP"
    namespace = ""
    cluster = "default"
    username = ""
    password = ""
  }
}

config {
  # file、nacos 、apollo、zk、consul、etcd3
  type = "nacos"  #seata服务的配置文件类型,可以是file、nacos等

  nacos {
    serverAddr = "127.0.0.1:8848"
    namespace = ""
    group = "SEATA_GROUP"
    username = ""
    password = ""
    application = "seata-server"
  }
}


2.3 如过使用nacos配置中心,则需要config.txt文件

https://github.com/seata/seata/tree/develop/script/config-center

在这里插入图片描述

config.tex精简后的配置如下:

#事务分组——my_test_tx_group 这值会在我们客户端对应,需要注意
service.vgroupMapping.my_test_tx_group=default
service.default.grouplist=127.0.0.1:8091
store.mode=db
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.jdbc.Driver
store.db.url=jdbc:mysql://ip::3306/seata?useUnicode=true
store.db.user=username
store.db.password=password
store.db.minConn=5
store.db.maxConn=30
store.db.globalTable=global_table
store.db.branchTable=branch_table
store.db.queryLimit=100
store.db.lockTable=lock_table
store.db.maxWait=5000


2.4 上传config.txt到配置中心

在这里插入图片描述

下载nacos文件下面的nacos-config.sh文件

然后执行

nacos-config.sh -h 127.0.0.1 -p 8848



客户端配置

在这里插入图片描述


1) 需要客户端操作的数据库当中建立undo_log表;


这个表用来实现sql反向补偿也就是回滚的信息


-- for AT mode you must to init this sql for you business database. the seata server not need it.
CREATE TABLE IF NOT EXISTS `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
  AUTO_INCREMENT = 1
  DEFAULT CHARSET = utf8 COMMENT ='AT transaction mode undo table';


2) pom文件添加seata依赖

		<dependency>
            <groupId>io.seata</groupId>
            <artifactId>seata-spring-boot-starter</artifactId>
            <version>1.2.0</version>
        </dependency>
      
		<dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-seata</artifactId>
            <!-- 剔除spring-cloud-alibaba默认版本,引入了自己对应的版本 -->
            <exclusions>
                <exclusion>
                    <artifactId>io.seata</artifactId>
                    <groupId>seata-spring-boot-starter</groupId>
                </exclusion>
            </exclusions>
		</dependency>


3) application.yml中添加seata配置

seata:
  enabled: true
  application-id: applicationName
  tx-service-group: my_test_tx_group
  enable-auto-data-source-proxy: true
  use-jdk-proxy: false
  config:
    type: nacos
    nacos:
      namespace:
      serverAddr: localhost:你的端口
      group: SEATA_GROUP
      userName: ""
      password: ""
  registry:
    type: nacos
    nacos:
      application: seata-server
      server-addr: localhost:你的端口
      namespace:
      userName: ""
      password: ""


注意:需要在每一个参与分布式事务的服务中添加该配置


4) 使用分布式事务


@GlobalTransactional:

分布式事务注解

比如A->B->C,那么只需要在A服务方法上加上

@GlobalTransactional

注解就好

A为TM事务管理者

@RestController
public class A{
	@GlobalTransactional
	@GetMapping("xxxxxx")
	public string a(){
		通过feign调用b
	}
}

每一个参与分布式事务的服务中添加该配置**


5) 数据源代理

这个是要特别注意的地方,seata对数据源做了代理和接管,在每个参与分布式事务的服务中,都要做如下配置:

/**
 * 数据源代理
 */
@Configuration
public class DataSourceConfiguration {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        return druidDataSource;
    }

    @Primary
    @Bean("dataSource")
    public DataSourceProxy dataSource(DataSource druidDataSource){
        return new DataSourceProxy(druidDataSource);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSourceProxy dataSourceProxy)throws Exception{
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSourceProxy);
        sqlSessionFactoryBean.setMapperLocations(
            					new PathMatchingResourcePatternResolver()
        										.getResources("classpath*:/mapper/*.xml"));
        sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
        return sqlSessionFactoryBean.getObject();
    }

}



版权声明:本文为qq_42019951原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。