• SpringBoot整合Seata1.5.1


    1、Seata 是什么?

    Seata 是一款开源的分布式事务解决方案,致力于提供高性能和简单易用的分布式事务服务。Seata 将为用户提供了 AT、TCC、SAGA 和 XA 事务模式,为用户打造一站式的分布式解决方案。

    2、下载

    Windows版本: seata-server-1.5.1.zip
    Linux版本: seata-server-1.5.1.tar.gz

    3、建表(仅db)

    -- -------------------------------- 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_status_gmt_modified` (`status` , `gmt_modified`),
        KEY `idx_transaction_id` (`transaction_id`)
    ) ENGINE = InnoDB
      DEFAULT CHARSET = utf8mb4;
    
    -- 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 = utf8mb4;
    
    -- the table to store lock data
    CREATE TABLE IF NOT EXISTS `lock_table`
    (
        `row_key`        VARCHAR(128) NOT NULL,
        `xid`            VARCHAR(128),
        `transaction_id` BIGINT,
        `branch_id`      BIGINT       NOT NULL,
        `resource_id`    VARCHAR(256),
        `table_name`     VARCHAR(32),
        `pk`             VARCHAR(36),
        `status`         TINYINT      NOT NULL DEFAULT '0' COMMENT '0:locked ,1:rollbacking',
        `gmt_create`     DATETIME,
        `gmt_modified`   DATETIME,
        PRIMARY KEY (`row_key`),
        KEY `idx_status` (`status`),
        KEY `idx_branch_id` (`branch_id`),
        KEY `idx_xid_and_branch_id` (`xid` , `branch_id`)
    ) ENGINE = InnoDB
      DEFAULT CHARSET = utf8mb4;
    
    CREATE TABLE IF NOT EXISTS `distributed_lock`
    (
        `lock_key`       CHAR(20) NOT NULL,
        `lock_value`     VARCHAR(20) NOT NULL,
        `expire`         BIGINT,
        primary key (`lock_key`)
    ) ENGINE = InnoDB
      DEFAULT CHARSET = utf8mb4;
    
    INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('AsyncCommitting', ' ', 0);
    INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('RetryCommitting', ' ', 0);
    INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('RetryRollbacking', ' ', 0);
    INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('TxTimeoutCheck', ' ', 0);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73

    4、修改store.mode

    启动包: seata–>conf–>application.yml,修改store.mode=“db或者redis”
    源码: 根目录–>seata-server–>resources–>application.yml,修改store.mode=“db或者redis”

    1.5.0以下版本:
    启动包: seata–>conf–>file.conf,修改store.mode=“db或者redis”
    源码: 根目录–>seata-server–>resources–>file.conf,修改store.mode=“db或者redis”

    5、修改数据库连接|redis属性配置

    启动包: seata–>conf–>application.example.yml中附带额外配置,将其db|redis相关配置复制至application.yml,进行修改store.db或store.redis相关属性。
    源码: 根目录–>seata-server–>resources–>application.example.yml中附带额外配置,将其db|redis相关配置复制至application.yml,进行修改store.db或store.redis相关属性。

    1.5.0以下版本:

    启动包: seata–>conf–>file.conf,修改store.db或store.redis相关属性。
    源码: 根目录–>seata-server–>resources–>file.conf,修改store.db或store.redis相关属性。

    注意:数据库连接或redis属性配置可以放在nacos中,并修改application.yml中配置:
    seata:
      config:
        # support: nacos 、 consul 、 apollo 、 zk  、 etcd3
        type: nacos  #此处类型修改为naocs
        nacos:
          server-addr: 127.0.0.1:8848
          namespace:   #如果nacos中所有的配置文件都放在默认的public下,此处可不填
          group: SEATA_GROUP
          username:
          password:
          ##if use MSE Nacos with auth, mutex with username/password attribute
          #access-key: ""
          #secret-key: ""
          data-id: seataServer.properties
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    6、修改注册中心,此处以naocs为例

    启动包: seata–>conf–>application.example.yml中附带额外配置,将其registry.type.nacos相关配置复制至application.yml,进行修改registry.naocs相关属性。

    seata:
    	registry:
        # support: nacos, eureka, redis, zk, consul, etcd3, sofa
        type: nacos
        nacos:
          application: seata-server
          server-addr: 127.0.0.1:8848
          group: SEATA_GROUP
          namespace:
          cluster: default
          username:
          password:
          ##if use MSE Nacos with auth, mutex with username/password attribute
          #access-key: ""
          #secret-key: ""
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    7、修改配置中心,此处以naocs为例

    启动包: seata–>conf–>application.example.yml中附带额外配置,将其config.type.nacos相关配置复制至application.yml,进行修改config.naocs相关属性。

    seata:
      config:
        # support: nacos, consul, apollo, zk, etcd3
        type: nacos
        nacos:
          server-addr: 127.0.0.1:8848
          namespace:
          group: SEATA_GROUP
          username:
          password:
          ##if use MSE Nacos with auth, mutex with username/password attribute
          #access-key: ""
          #secret-key: ""
          data-id: seataServer.properties
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    8、Naocs配置

    在这里插入图片描述

    #For details about configuration items, see https://seata.io/zh-cn/docs/user/configurations.html
    #Transport configuration, for client and server
    transport.type=TCP
    transport.server=NIO
    transport.heartbeat=true
    transport.enableTmClientBatchSendRequest=false
    transport.enableRmClientBatchSendRequest=true
    transport.enableTcServerBatchSendResponse=false
    transport.rpcRmRequestTimeout=30000
    transport.rpcTmRequestTimeout=30000
    transport.rpcTcRequestTimeout=30000
    transport.threadFactory.bossThreadPrefix=NettyBoss
    transport.threadFactory.workerThreadPrefix=NettyServerNIOWorker
    transport.threadFactory.serverExecutorThreadPrefix=NettyServerBizHandler
    transport.threadFactory.shareBossWorker=false
    transport.threadFactory.clientSelectorThreadPrefix=NettyClientSelector
    transport.threadFactory.clientSelectorThreadSize=1
    transport.threadFactory.clientWorkerThreadPrefix=NettyClientWorkerThread
    transport.threadFactory.bossThreadSize=1
    transport.threadFactory.workerThreadSize=default
    transport.shutdown.wait=3
    transport.serialization=seata
    transport.compressor=none
    
    #Transaction routing rules configuration, only for the client
    service.vgroupMapping.default_tx_group=default
    #If you use a registry, you can ignore it
    service.default.grouplist=127.0.0.1:8091
    service.enableDegrade=false
    service.disableGlobalTransaction=false
    
    #Transaction rule configuration, only for the client
    client.rm.asyncCommitBufferLimit=10000
    client.rm.lock.retryInterval=10
    client.rm.lock.retryTimes=30
    client.rm.lock.retryPolicyBranchRollbackOnConflict=true
    client.rm.reportRetryCount=5
    client.rm.tableMetaCheckEnable=true
    client.rm.tableMetaCheckerInterval=60000
    client.rm.sqlParserType=druid
    client.rm.reportSuccessEnable=false
    client.rm.sagaBranchRegisterEnable=false
    client.rm.sagaJsonParser=fastjson
    client.rm.tccActionInterceptorOrder=-2147482648
    client.tm.commitRetryCount=5
    client.tm.rollbackRetryCount=5
    client.tm.defaultGlobalTransactionTimeout=60000
    client.tm.degradeCheck=false
    client.tm.degradeCheckAllowTimes=10
    client.tm.degradeCheckPeriod=2000
    client.tm.interceptorOrder=-2147482648
    client.undo.dataValidation=true
    client.undo.logSerialization=jackson
    client.undo.onlyCareUpdateColumns=true
    server.undo.logSaveDays=7
    server.undo.logDeletePeriod=86400000
    client.undo.logTable=undo_log
    client.undo.compress.enable=true
    client.undo.compress.type=zip
    client.undo.compress.threshold=64k
    #For TCC transaction mode
    tcc.fence.logTableName=tcc_fence_log
    tcc.fence.cleanPeriod=1h
    
    #Log rule configuration, for client and server
    log.exceptionRate=100
    
    #Transaction storage configuration, only for the server. The file, DB, and redis configuration values are optional.
    store.mode=file
    store.lock.mode=file
    store.session.mode=file
    #Used for password encryption
    store.publicKey=
    
    #If `store.mode,store.lock.mode,store.session.mode` are not equal to `file`, you can remove the configuration block.
    store.file.dir=file_store/data
    store.file.maxBranchSessionSize=16384
    store.file.maxGlobalSessionSize=512
    store.file.fileWriteBufferCacheSize=16384
    store.file.flushDiskMode=async
    store.file.sessionReloadReadSize=100
    
    #These configurations are required if the `store mode` is `db`. If `store.mode,store.lock.mode,store.session.mode` are not equal to `db`, you can remove the configuration block.
    store.db.datasource=druid
    store.db.dbType=mysql
    store.db.driverClassName=com.mysql.jdbc.Driver
    store.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true&rewriteBatchedStatements=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.distributedLockTable=distributed_lock
    store.db.queryLimit=100
    store.db.lockTable=lock_table
    store.db.maxWait=5000
    
    #These configurations are required if the `store mode` is `redis`. If `store.mode,store.lock.mode,store.session.mode` are not equal to `redis`, you can remove the configuration block.
    store.redis.mode=single
    store.redis.single.host=127.0.0.1
    store.redis.single.port=6379
    store.redis.sentinel.masterName=
    store.redis.sentinel.sentinelHosts=
    store.redis.maxConn=10
    store.redis.minConn=1
    store.redis.maxTotal=100
    store.redis.database=0
    store.redis.password=
    store.redis.queryLimit=100
    
    #Transaction rule configuration, only for the server
    server.recovery.committingRetryPeriod=1000
    server.recovery.asynCommittingRetryPeriod=1000
    server.recovery.rollbackingRetryPeriod=1000
    server.recovery.timeoutRetryPeriod=1000
    server.maxCommitRetryTimeout=-1
    server.maxRollbackRetryTimeout=-1
    server.rollbackRetryTimeoutUnlockEnable=false
    server.distributedLockExpireTime=10000
    server.xaerNotaRetryTimeout=60000
    server.session.branchAsyncQueueSize=5000
    server.session.enableBranchAsyncRemove=false
    server.enableParallelRequestHandle=false
    
    #Metrics configuration, only for the server
    metrics.enabled=false
    metrics.registryType=compact
    metrics.exporterList=prometheus
    metrics.exporterPrometheusPort=9898
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130

    注:Seata 启动报错 can not get cluster name in registry config 'service.vgroupMapping.XXX', please make sure registry config correct
    需要在nacos中再添加service.vgroupMapping.XXXX配置值为default

    9、启动

    • 源码启动: 执行ServerApplication.java的main方法
    • 命令启动: seata-server.sh -h 127.0.0.1 -p 8091 -m db
    • 双击seata-server.bat或 ./seata-server.sh方式启动

    1.5.0以下版本

    • 源码启动: 执行Server.java的main方法
    • 命令启动: seata-server.sh -h 127.0.0.1 -p 8091 -m db -n 1 -e test
    -h: 注册到注册中心的ip
    -p: Server rpc 监听端口
    -m: 全局事务会话信息存储模式,file、db、redis,优先读取启动参数 (Seata-Server 1.3及以上版本支持redis)
    -n: Server node,多个Server时,需区分各自节点,用于生成不同区间的transactionId,以免冲突
    -e: 多环境配置参考 http://seata.io/en-us/docs/ops/multi-configuration-isolation.html
    
    • 1
    • 2
    • 3
    • 4
    • 5

    – 注: 堆内存建议分配2G,堆外内存1G

    10、业务系统集成Client

    版本对应关系

    官方版本对应说明

    注意事项

    • seata-spring-boot-starter
    内置GlobalTransactionScanner自动初始化功能,若外部实现初始化,请参考SeataAutoConfiguration保证依赖加载顺序
    默认开启数据源自动代理,可配置seata.enable-auto-data-source-proxy: false关闭
    
    • 1
    • 2
    • spring-cloud-starter-alibaba-seata
    2.1.0内嵌seata-all 0.7.1,2.1.1内嵌seata-all 0.9.0,2.2.0内嵌seata-spring-boot-starter 1.0.0, 2.2.1内嵌seata-spring-boot-starter 1.1.0
    
    • 1
    2.1.0和2.1.1兼容starter解决方案:
    @SpringBootApplication注解内exclude掉spring-cloud-starter-alibaba-seata内的com.alibaba.cloud.seata.GlobalTransactionAutoConfiguration
    
    • 1
    • 2
    • spring-cloud-starter-alibaba-seata推荐依赖配置方式
    		<dependency>
               <groupId>io.seatagroupId>
               <artifactId>seata-spring-boot-starterartifactId>
               <version>1.5.1version>
           dependency>
           <dependency>
               <groupId>com.alibaba.cloudgroupId>
               <artifactId>spring-cloud-starter-alibaba-seataartifactId>
               <version>2.2.8.RELEASEversion>
               <exclusions>
                   <exclusion>
                       <groupId>io.seatagroupId>
                       <artifactId>seata-spring-boot-starterartifactId>
                   exclusion>
               exclusions>
           dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    undo_log建表、配置参数(仅AT模式)

    -- 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       NOT NULL COMMENT 'branch transaction id',
        `xid`           VARCHAR(128) 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 = utf8mb4 COMMENT ='AT transaction mode undo table';
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    application.yml配置

    seata:
      config:
        type: nacos
        nacos:
          server-addr: 127.0.0.1:8848
          group: SEATA_GROUP
          namespace:
          dataId: seataServer.properties
          username: nacos
          password: nacos
      registry:
        type: nacos
        nacos:
          server-addr: 127.0.0.1:8848
          application: seata-server
          group : DEFAULT_GROUP
          namespace:
          username: nacos
          password: nacos
      service:
        #指定事务分组至集群映射关系(等号右侧的集群名需要与Seata-server注册到Nacos的cluster保持一致)
        vgroup-mapping:
          default_tx_group: fsp_tx_group
      tx-service-group: fsp_tx_group
    #    grouplist:
    #      fsp_tx_group: 127.0.0.1:8091
    #另外:若Client不通过Nacos获取seata-server服务信息,而是直接指定seata-server服务端节点的IP和端口信息,则可将以上application.properties中涉及nacos几个配置改为如两个配置:
    #seata.registry.type=file ----> 不推荐在正式环境使用
    #seata.service.grouplist.cluster_beijing=127.0.0.1:8091 ----> vgroup-mapping(服务端cluster)各个seata-server节点信息
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    查看参数配置介绍

    seata.tx-service-group=my_test_tx_group ---------------> 事务分组配置(在v1.5之后默认值为default_tx_group)
    1、读取配置 通过FileConfiguration本地加载file.conf的配置参数
    2、获取事务分组(服务启动时加载配置) spring/springboot可配置在yml、properties中,对应值"my_test_tx_group"即为事务分组名,若不配置则默认以:spring.application.name值+"-seata-service-group"拼接后的字符串作为分组名
    3、查找TC集群名 拿到事务分组名"my_test_tx_group"拼接成"service.vgroupMapping.my_test_tx_group"查找TC集群名clusterName为"default"
    4、查询TC服务 拼接"service."+clusterName+".grouplist"找到真实TC服务地址127.0.0.1:8091
    
    • 1
    • 2
    • 3
    • 4
    • 5

    数据源代理(不支持自动和手动配置并存)

    1、如果使用seata-all

    • 0.9.0版本开始seata支持自动代理数据源
    1.1.0: seata-all取消属性配置,改由注解@EnableAutoDataSourceProxy开启,并可选择jdk proxy或者cglib proxy
    1.0.0: client.support.spring.datasource.autoproxy=true
    0.9.0: support.spring.datasource.autoproxy=true
    
    • 1
    • 2
    • 3

    如果采用XA模式,@EnableAutoDataSourceProxy(dataSourceProxyMode = "XA")

    • 手动配置可参考下方的例子
    @Primary
    @Bean("dataSource")
    public DataSource dataSource(DataSource druidDataSource) {
        //AT 代理 二选一
        return new DataSourceProxy(druidDataSource);
        //XA 代理
        return new DataSourceProxyXA(druidDataSource)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2、如果使用seata-starter

    • 使用自动代理数据源时,如果使用XA模式还需要调整配置文件
      application.properties
    seata.data-source-proxy-mode=XA  
    
    • 1

    application.yml

    seata:
      data-source-proxy-mode: XA
    
    • 1
    • 2
    • 如何关闭seata-spring-boot-starter的数据源自动代理?
      application.properties
    seata.enable-auto-data-source-proxy=false  
    
    • 1

    application.yml

    seata:
      enable-auto-data-source-proxy: false
    
    • 1
    • 2

    初始化GlobalTransactionScanner

    • 手动
    @Bean
           public GlobalTransactionScanner globalTransactionScanner() {
               String applicationName = this.applicationContext.getEnvironment().getProperty("spring.application.name");
               String txServiceGroup = this.seataProperties.getTxServiceGroup();
               if (StringUtils.isEmpty(txServiceGroup)) {
                   txServiceGroup = applicationName + "-fescar-service-group";
                   this.seataProperties.setTxServiceGroup(txServiceGroup);
               }
       
               return new GlobalTransactionScanner(applicationName, txServiceGroup);
           }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 自动,引入seata-spring-boot-starter、spring-cloud-starter-alibaba-seata等jar

    实现xid跨服务传递

    • 手动 参考源码integration文件夹下的各种rpc实现 module
    • 自动 springCloud用户可以引入spring-cloud-starter-alibaba-seata,内部已经实现xid传递

    9、业务使用

    注解拦截

    全局事务

    @GetMapping(value = "testCommit")
    @GlobalTransactional
    public Object testCommit(@RequestParam(name = "id",defaultValue = "1") Integer id,
        @RequestParam(name = "sum", defaultValue = "1") Integer sum) {
        Boolean ok = productService.reduceStock(id, sum);
        if (ok) {
            LocalDateTime now = LocalDateTime.now();
            Orders orders = new Orders();
            orders.setCreateTime(now);
            orders.setProductId(id);
            orders.setReplaceTime(now);
            orders.setSum(sum);
            orderService.save(orders);
            return "ok";
        } else {
            return "fail";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    TCC

     * 定义两阶段提交 name = 该tcc的bean名称,全局唯一 commitMethod = commit 为二阶段确认方法 rollbackMethod = rollback 为二阶段取消方法
     * useTCCFence=true 为开启防悬挂
     * BusinessActionContextParameter注解 传递参数到二阶段中
     *
     * @param params  -入参
     * @return String
     */
    @TwoPhaseBusinessAction(name = "beanName", commitMethod = "commit", rollbackMethod = "rollback", useTCCFence = true)
    public void insert(@BusinessActionContextParameter(paramName = "params") Map<String, String> params) {
        logger.info("此处可以预留资源,或者利用tcc的特点,与AT混用,二阶段时利用一阶段在此处存放的消息,通过二阶段发出,比如redis,mq等操作");
    }
    
    /**
     * 确认方法、可以另命名,但要保证与commitMethod一致 context可以传递try方法的参数
     *
     * @param context 上下文
     * @return boolean
     */
    public void commit(BusinessActionContext context) {
        logger.info("预留资源真正处理,或者发出mq消息和redis入库");
    }
    
    /**
     * 二阶段取消方法
     *
     * @param context 上下文
     * @return boolean
     */
    public void rollback(BusinessActionContext context) {
        logger.info("预留资源释放,或清除一阶段准备让二阶段提交时发出的消息缓存");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    全局事务

    全局事务

    @Bean
        public AspectTransactionalInterceptor aspectTransactionalInterceptor () {
            return new AspectTransactionalInterceptor();
        }
    
        @Bean
        public Advisor txAdviceAdvisor(AspectTransactionalInterceptor aspectTransactionalInterceptor ) {
            AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
            pointcut.setExpression("配置切点表达式使全局事务拦截器生效");
            return new DefaultPointcutAdvisor(pointcut, aspectTransactionalInterceptor);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
  • 相关阅读:
    vue脚手架搭建2022年6月版本(保姆级)
    【MATLAB源码-第141期】基于matlab的免疫优化算法在物流配送中心选址应用仿真,输出选址图以及算法适应度曲线。
    SpringBoot启动时加载
    处理不平衡数据的十大 Python 库
    (4E)-TCO-PEG4-acid,1802913-21-8物理性质分享
    Linux系统之部署Linux命令大全搜索工具
    Windows 下 MSVC 编译器在 CMake 生成时提示 RC failed 或库文件缺失
    Mac下使用nvm,执行微信小程序自定义处理命令失败
    python设计模式11:观察者模式
    软件管理 - yum - rpm -本地yum源 - 局域网远程yum源 - 阿里云镜像 - 克隆阿里云镜像源
  • 原文地址:https://blog.csdn.net/weixin_46416295/article/details/126332070