Nacos2.1.2+Seata1.5.2+Mysql8+SpringCloud+Feign实现分布式事务笔记

搭建环境可以使用docker或是手动自己构建

nacos比较简单也可以参考:

ubuntu 22 Docker部署Nacos_山塘小鱼儿的博客-CSDN博客_ubuntu docker安装部署

seata的docker部署

sudo docker pull seataio/seata-server:1.5.2
sudo docker run -d --name seata-server -p 8091:8091 -p 7091:7091  seataio/seata-server:1.5.2
sudo docker exec -it seata-server sh
mkdir -p /data/seata
sudo mkdir -p /data/seata
sudo docker cp seata-server:/seata-server/resources /data/seata
cd /data/seata/resources
sudo nano application.yml
sudo docker ps -a
sudo docker stop seata-server
sudo docker rm -f seata-server
sudo docker run -d --name seata-server -p 8091:8091 -p 7091:7091  -e SEATA_IP=public-ip  -v /data/seata/resources/:/seata-server/resources seataio/seata-server:1.5.2
sudo docker update --restart=always seata-server #设置自动启动

1.启动nacos服务,nacos/nacos登录http://nacos-ip:8848

Nacos2.1.2+Seata1.5.2+Mysql8+SpringCloud+Feign实现分布式事务笔记_第1张图片

2.修改Seata的配置文件,注册到nacos上:

application.yml

spring:
  application:
    name: seata-server

logging:
  config: classpath:logback-spring.xml
  file:
    path: ${user.home}/logs/seata
  extend:
    logstash-appender:
      destination: 127.0.0.1:4560
    kafka-appender:
      bootstrap-servers: 127.0.0.1:9092
      topic: logback_to_logstash

seata:
  config:
    # support: nacos 、 consul 、 apollo 、 zk  、 etcd3
    type: nacos
    nacos:
      server-addr: nacos-ip:8848
      namespace:
      group: SEATA_GROUP
      username: nacos
      password: nacos
      ##if use MSE Nacos with auth, mutex with username/password attribute
      #access-key: ""
      #secret-key: ""
      data-id: seataServer.properties
  registry:
    # support: nacos 、 eureka 、 redis 、 zk  、 consul 、 etcd3 、 sofa
    type: nacos
    nacos:
      application: seata-server
      server-addr: nacos-ip:8848
      group: SEATA_GROUP
      namespace:
      cluster: default
      username: nacos
      password: nacos
  server:
    service-port: 8091 #If not configured, the default is '${server.port} + 1000'
    max-commit-retry-timeout: -1
    max-rollback-retry-timeout: -1
    rollback-retry-timeout-unlock-enable: false
    enable-check-auth: true
    enable-parallel-request-handle: true
    retry-dead-threshold: 130000
    xaer-nota-retry-timeout: 60000
    recovery:
      handle-all-session-period: 1000
    undo:
      log-save-days: 7
      log-delete-period: 86400000
    session:
      branch-async-queue-size: 5000 #branch async remove queue size
      enable-branch-async-remove: false #enable to asynchronous remove branchSession
  metrics:
    enabled: false
    registry-type: compact
    exporter-list: prometheus
    exporter-prometheus-port: 9898
  transport:
    rpc-tc-request-timeout: 30000
    enable-tc-server-batch-send-response: false
    shutdown:
      wait: 3
    thread-factory:
      boss-thread-prefix: NettyBoss
      worker-thread-prefix: NettyServerNIOWorker
      boss-thread-size: 1
  security:
    secretKey:
    tokenValidityInMilliseconds: 1800000
console:
  user:
    username: seata
    password: seata

nacos配置seata

 详情

dataId:seataServer.properties

group:SEATA_GROUP

content:properties类型

#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.my_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=db

#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.cj.jdbc.Driver
store.db.url=jdbc:mysql://mysql-ip:3306/seata?rewriteBatchedStatements=true
store.db.user=
store.db.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

#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

dataId:service.vgroupMapping.my_tx_group=default

与上文中相一致

group:SEATA_GROUP

content:text类型

default

根据seata中的sql,位置:\seata\script\server\db\mysql.sql 创建表,库名为seate

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

启动seata,观察nacos注册情况

Nacos2.1.2+Seata1.5.2+Mysql8+SpringCloud+Feign实现分布式事务笔记_第2张图片

 3.seata已经注册到nacos上以后,开始编写程序代码

业务库中必须建立一个分布式事务的表undo_log,使用分布式事物的服务,每一个都要建立这个表

CREATE TABLE `undo_log` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `branch_id` bigint NOT NULL,
  `xid` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
  `context` varchar(128) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
  `rollback_info` longblob NOT NULL,
  `log_status` int NOT NULL,
  `log_created` datetime NOT NULL,
  `log_modified` datetime NOT NULL,
  `ext` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 ROW_FORMAT=DYNAMIC;

程序中改动主要是微服务的配置文件,添加seata相关配置

server:
  port: 5001
spring:
  application:
    name: test-bis
  cloud:
    nacos:
      discovery:
        server-addr: nacos-ip:8848
        username: nacos
        password: nacos
        namespace:
        group: SEATA_GROUP
  datasource:
    dynamic:
      datasource:
        master:
          url: jdbc:mysql://mysql-ip:3306/seata_storage?characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong
          username: 
          password: 
        store:
          url: jdbc:mysql://mysql-ip:3306/seata_storage?characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong
          username: 
          password: 
      seata: true
seata:
  application-id: ${spring.application.name}
  enable-auto-data-source-proxy: false
  config:
    type: nacos
    nacos:
      server-addr: nacos-ip:8848
      username: nacos
      password: nacos
      namespace:
      group: SEATA_GROUP
      dataId: "seataServer.properties"
  registry:
    type: nacos
    nacos:
      application: seata-server
      server-addr: nacos-ip:8848
      group: SEATA_GROUP
      namespace:
      username: nacos
      password: nacos
   

pom文件的配置,工程总配置:


        8
        8
        Hoxton.SR6
        2.2.8.RELEASE
        2.3.2.RELEASE
        8.0.18
        3.3.2
        1.18.24
        3.2.0
    

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
            
                com.alibaba.cloud
                spring-cloud-alibaba-dependencies
                ${spring-cloud-alibaba.version}
                pom
                import
            
            
                org.springframework.boot
                spring-boot-dependencies
                ${spring-boot.version}
                pom
                import
            
            
                io.seata
                seata-spring-boot-starter
                1.5.2
            

            
                mysql
                mysql-connector-java
                ${mysql.version}
            
            
                com.baomidou
                mybatis-plus-boot-starter
                ${mybatis-plus.version}
            
            
            
                org.projectlombok
                lombok
                ${lombok.version}
            
       
        com.baomidou
        dynamic-datasource-spring-boot-starter
        ${dynamic.version}
      
        
    

子工程的配置


        8
        8
    

    

        
            org.springframework.boot
            spring-boot-starter
        

        
            com.alibaba.cloud
            spring-cloud-starter-alibaba-nacos-discovery
        
        
            io.seata
            seata-spring-boot-starter
        

        
        
            com.alibaba.cloud
            spring-cloud-starter-alibaba-seata
        

        
            org.springframework.boot
            spring-boot-starter-web
        
        
            mysql
            mysql-connector-java
        
        
            com.baomidou
            mybatis-plus-boot-starter
        
        
            org.projectlombok
            lombok
        
       

开启分布式服务的注解

import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Override
@Transactional(rollbackFor = Exception.class)
@GlobalTransactional(rollbackFor = Exception.class)

Feign调用开启

//@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, DruidDataSourceAutoConfigure.class})使用druid单数据源需要禁用spring自动配置
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients(basePackages = {"my.api.feign"})#引用的自定义feign的api
public class BisApplication {

    public static void main(String[] args) {
        SpringApplication.run(BisApplication.class, args);
    }

}

Feign的api工程的实现

pom


        8
        8
    

     
            com.alibaba.cloud
            spring-cloud-starter-alibaba-seata
     
    

代码:

@FeignClient(value ="test-bis")
//这个值就是微服务注册nacos的name
//spring:
// application:
//  name: test-bis
public interface ProviderClient {

    @PostMapping("/test/provider/add")//test-provider服务中controller的调用路径
    String add(@RequestParam("uuid") Long uuId, @RequestParam("count") BigDecimal count);
}

打好包后,其他的微服务可以引用这个client,相互调用,在service方法上方加上

import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Transactional(rollbackFor = Exception.class)

@GlobalTransactional(rollbackFor = Exception.class)

注解,调用时便会开启全局事务了

主调程序的写法

    @Resource
    private ProviderClient  providerClient ;
    @Override
    @Transactional(rollbackFor = Exception.class)
    @GlobalTransactional(rollbackFor = Exception.class)
    public void mainService(Request request) {
   
        System.out.println("seata全局事务id====================>"+ RootContext.getXID());
        providerClient.add(x,x);
}

被调用的服务的service写法

@Service
public class STServiceImpl implements STService{

    @Autowired
    StMapper stdao;
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    public void add() {
        System.out.println("seata全局事务id====================>"+ RootContext.getXID());
        St st = new St();
        st.setSii("2");
        st.setTii("3");
        stdao.insert(st);
//      int i =1/0;
    }
}

seata全局事务id====================>x.x.x.x:8091:8034757401001071416

以上便可以达到全局回滚和提交的分布式事务的效果了。

以上做法是service一个方法中调用A,B,C三个微服务的事务,但是实际情况可能更复杂,是链路调用的方式,如果链路调用,A-->B-->C,那么调用过程中需要上一个服务传递xid,并且下一个服务绑定xid,才可以全部注册进全局事务里面,事务正常才能回滚。

A服务代码

String xid = RootContext.getXID();//从A服务中心拿到全局xid

BfeignClient.add(xid);//传到B的服务中去

B服务的代码

//先绑定当前事务
RootContext.bind(xid);

dao.save();

你可能感兴趣的:(spring,cloud,seata,Feign,nacos)