seata + dynamic-datasource + Springboot + mybatis-plus 集成分布式事务操作

下载 seata
官方地址:https://seata.io/zh-cn/blog/download.html

数据库脚本

-- -------------------------------- 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;

修改配置文件 file.conf 和 registry.conf配置
file.conf

service {
  #transaction service group mapping
  vgroupMapping.fbs_tx_group = "seata-server" ##修改
  #only support when registry.type=file, please don't set multiple addresses
  seata-server.grouplist = "192.168.0.2:8089" ##修改
  #degrade, current not support
  enableDegrade = false
  #disable seata
  disableGlobalTransaction = false
}
## transaction log store, only used in seata-server
store {
  ## store mode: file、db、redis
  mode = "db" ##修改

  ## file store property
  file {
    ## store location dir
    dir = "sessionStore"
    # branch session size , if exceeded first try compress lockkey, still exceeded throws exceptions
    maxBranchSessionSize = 16384
    # globe session size , if exceeded throws exceptions
    maxGlobalSessionSize = 512
    # file buffer size , if exceeded allocate new buffer
    fileWriteBufferCacheSize = 16384
    # when recover batch read size
    sessionReloadReadSize = 100
    # async, sync
    flushDiskMode = async
  }

  ## database store property
  db { ##修改成自己的地址
    ## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp)/HikariDataSource(hikari) etc.
    datasource = "druid"
    ## mysql/oracle/postgresql/h2/oceanbase etc.
    dbType = "mysql"
    driverClassName = "com.mysql.cj.jdbc.Driver"
    url = "jdbc:mysql://127.0.0.1:3306/db_seata?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai"
    user = "root"
    password = "root"
    minConn = 5
    maxConn = 100
    globalTable = "global_table"
    branchTable = "branch_table"
    lockTable = "lock_table"
    queryLimit = 100
    maxWait = 5000
  }

  ## redis store property
  redis {
    host = "127.0.0.1"
    port = "6379"
    password = ""
    database = "0"
    minConn = 1
    maxConn = 10
    maxTotal = 100
    queryLimit = 100
  }

}

registry.conf

registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "eureka"  ##修改
  loadBalance = "RandomLoadBalance"
  loadBalanceVirtualNodes = 10
  
  nacos {
    application = "seata-server"
    serverAddr = "127.0.0.1:8848"
    group = "SEATA_GROUP"
    namespace = ""
    cluster = "default"
    username = ""
    password = ""
  }
  eureka {
    serviceUrl = "http://127.0.0.1:8761/eureka/"  ##修改
    application = "seata-server"  ##修改
    weight = "1"
  }
  redis {
    serverAddr = "localhost:6379"
    db = 0
    password = ""
    cluster = "default"
    timeout = 0
  }
  zk {
    cluster = "default"
    serverAddr = "127.0.0.1:2181"
    sessionTimeout = 6000
    connectTimeout = 2000
    username = ""
    password = ""
  }
  consul {
    cluster = "default"
    serverAddr = "127.0.0.1:8500"
  }
  etcd3 {
    cluster = "default"
    serverAddr = "http://localhost:2379"
  }
  sofa {
    serverAddr = "127.0.0.1:9603"
    application = "default"
    region = "DEFAULT_ZONE"
    datacenter = "DefaultDataCenter"
    cluster = "default"
    group = "SEATA_GROUP"
    addressWaitTime = "3000"
  }
  file {
    name = "file.conf"
  }
}

config {
  # file、nacos 、apollo、zk、consul、etcd3
  type = "file"  ##修改
  nacos {
    serverAddr = "127.0.0.1:8848"
    namespace = ""
    group = "SEATA_GROUP"
    username = ""
    password = ""
  }
  consul {
    serverAddr = "127.0.0.1:8500"
  }
  apollo {
    appId = "seata-server"
    apolloMeta = "http://192.168.1.204:8801"
    namespace = "application"
    apolloAccesskeySecret = ""
  }
  zk {
    serverAddr = "127.0.0.1:2181/config"
    sessionTimeout = 6000
    connectTimeout = 2000
    username = ""
    password = ""
  }
  etcd3 {
    serverAddr = "http://localhost:2379"
  }
  file {
    name = "file.conf"
  }
}

服务端配置完成

启动命令 seata-server.bat -h 192.168.0.2 -p 8088 端口号可自己定义
Linux启动命令 ./seata-server.sh -h 192.168.0.2 -p 8088

客户端配置

客户端脚本

-- 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';

pom.xml
使用zookeeper做配置中心

<!--引入seata依赖-->

 			<!-- 动态数据源(重点) -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>${dynamic.version}</version>
        </dependency>
        <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-generator</artifactId>
                <version>${mybatis.version}</version>
            </dependency>
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>${mybatis.version}</version>
            </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-seata</artifactId>
            <version>${alibaba-seata.version}</version>
            <exclusions>
                <!-- 排除依赖 指定版本和服务器端一致 -->
                <exclusion>
                    <groupId>io.seata</groupId>
                    <artifactId>seata-all</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>io.seata</groupId>
                    <artifactId>seata-spring-boot-starter</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.seata</groupId>
            <artifactId>seata-all</artifactId>
            <version>${io-seata.version}</version>
            <exclusions>
                <exclusion>
                    <artifactId>druid</artifactId>
                    <groupId>com.alibaba</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>error_prone_annotations</artifactId>
                    <groupId>com.google.errorprone</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>checker-qual</artifactId>
                    <groupId>org.checkerframework</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.seata</groupId>
            <artifactId>seata-spring-boot-starter</artifactId>
            <version>${io-seata.version}</version>
        </dependency>
        <dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
            <version>${zkclient.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

配置文件 yam文件

spring:
  datasource:
    dynamic:
      seata: true ##dynamic开启支持seata
#seata 配置, 代替file.conf和registry.conf配置
seata:
  # 事务群组(可以每个应用独立取名,也可以使用相同的名字)
  tx-service-group: fbs_tx_group
  client:
    rm:
     lock:
       retry-interval: 30 #校验或占用全局锁次数 30次
       retry-times: 10 #校验或占用全局锁间隔 10s
    # 异步提交缓存队列长度(默认10000)
    #rm-async-commit-buffer-limit: 1000
    #support:
      # 数据源自动代理开关(默认false关闭)
    #  spring-datasource-autoproxy: true
    tm:
      commit-retry-count: 3 # 一阶段全局提交结果上报TC重试次数(默认1次,建议大于1)
      rollback-retry-count: 3 # 一阶段全局回滚结果上报TC重试次数(默认1次,建议大于1)
  registry:
    eureka:
      application: SEATA-SERVER
      service-url: http://127.0.0.1:8761/eureka/
  config:
    type: zk
    zk:
      server-addr: 127.0.0.1:2181/config
      connect-timeout: 2000
      session-timeout: 6000
  service:
    vgroup-mapping:
      # TC 集群(必须与seata-server保持一致)
      fbs_tx_group: seata-server
  enable-auto-data-source-proxy: false #是否开启数据自动处理
  application-id: ${spring.application.name}

zookeeper配置

/config/seata=client.log.exceptionRate=100
/config/seata=client.rm.asyncCommitBufferLimit=10000
/config/seata=client.rm.lock.retryInterval=10
/config/seata=client.rm.lock.retryPolicyBranchRollbackOnConflict=true
/config/seata=client.rm.lock.retryTimes=30
/config/seata=client.rm.reportRetryCount=5
/config/seata=client.rm.reportSuccessEnable=false
/config/seata=client.rm.sagaBranchRegisterEnable=false
/config/seata=client.rm.sqlParserType=druid
/config/seata=client.rm.tableMetaCheckEnable=false
/config/seata=client.tm.commitRetryCount=5
/config/seata=client.tm.defaultGlobalTransactionTimeout=6000
/config/seata=client.tm.degradeCheck=false
/config/seata=client.tm.rollbackRetryCount=5
/config/seata=client.undo.dataValidation=true
/config/seata=client.undo.logSerialization=jackson
/config/seata=client.undo.logTable=undo_log
/config/seata=server.enableCheckAuth=false
/config/seata=server.maxCommitRetryTimeout=-1
/config/seata=server.maxRollbackRetryTimeout=-1
/config/seata=server.recovery.asynCommittingRetryPeriod=1000
/config/seata=server.recovery.committingRetryPeriod=1000
/config/seata=server.recovery.rollbackingRetryPeriod=1000
/config/seata=server.recovery.timeoutRetryPeriod=1000
/config/seata=server.rollbackRetryTimeoutUnlockEnable=false
/config/seata=server.undo.logDeletePeriod=86400000
/config/seata=server.undo.logSaveDays=7
/config/seata=service.default.grouplist=47.104.214.224:8089
/config/seata=service.disableGlobalTransaction=false
/config/seata=service.enableDegrade=false
/config/seata=service.seata-server.grouplist=47.104.214.224:8089
/config/seata=service.vgroupMapping.fbs_tx_group=default
/config/seata=transport.compressor=none
/config/seata=transport.enableClientBatchSendRequest=false
/config/seata=transport.heartbeat=true
/config/seata=transport.serialization=seata
/config/seata=transport.server=NIO
/config/seata=transport.shutdown.wait=3
/config/seata=transport.threadFactory.bossThreadPrefix=NettyBoss
/config/seata=transport.threadFactory.bossThreadSize=1
/config/seata=transport.threadFactory.clientSelectorThreadPrefix=NettyClientSelector
/config/seata=transport.threadFactory.clientSelectorThreadSize=1
/config/seata=transport.threadFactory.clientWorkerThreadPrefix=NettyClientWorkerThread
/config/seata=transport.threadFactory.serverExecutorThreadPrefix=NettyServerBizHandler
/config/seata=transport.threadFactory.shareBossWorker=false
/config/seata=transport.threadFactory.workerThreadPrefix=NettyServerNIOWorker
/config/seata=transport.threadFactory.workerThreadSize=default
/config/seata=transport.type=TCP

配置完毕

开始使用 @GlobalTransactional(rollbackFor = Exception.class)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
dynamic-datasource是一个基于Spring Boot的多数据源组件,它提供了强大的功能,持Seata分布式事务,并适用于多种场景,包括纯粹多库、读写分离、一主多从和混合模式等。dynamic-datasource使用了HikariCP作为连接池来管理数据源连接。 HikariCP是一个高性能的JDBC连接池,它具有快速启动、低延迟和高吞吐量的特点。它通过使用轻量级的连接池实现和优化了连接的获取和释放过程,从而提高了数据库访问的性能。 使用dynamic-datasource和HikariCP可以实现动态切换数据源,并且能够根据业务需求灵活配置多个数据源。你可以在配置文件中定义多个数据源,并通过注解或者编程的方式来切换数据源。 以下是一个使用dynamic-datasource和HikariCP的示例配置: 1. 在pom.xml文件中添加dynamic-datasource和HikariCP的依赖: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>3.4.2</version> </dependency> <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <version>3.4.5</version> </dependency> ``` 2. 在application.properties或application.yml文件中配置数据源信息: ```yaml spring: datasource: dynamic: primary: master strict: false datasource: master: url: jdbc:mysql://localhost:3306/master username: root password: root driver-class-name: com.mysql.jdbc.Driver slave: url: jdbc:mysql://localhost:3306/slave username: root password: root driver-class-name: com.mysql.jdbc.Driver ``` 3. 在代码中使用@DS注解来切换数据源: ```java @Service public class UserService { @Autowired private UserMapper userMapper; @DS("master") public User getMasterUser(Long id) { return userMapper.selectById(id); } @DS("slave") public User getSlaveUser(Long id) { return userMapper.selectById(id); } } ``` 在上面的示例中,我们定义了两个数据源:master和slave。通过在方法上使用@DS注解,可以指定使用哪个数据源来执行数据库操作。 通过使用dynamic-datasource和HikariCP,你可以轻松实现多数据源的管理和切换,提高系统的灵活性和性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值