SpringCloud Alibaba整合Seata1.5.1 Seata1.5.2 以上版本 使用Nacos注册中心 Mysql存储 Docker部署SeataServer 分布式事务

前言

参考Seata官网

  • Seata1.5.X版本SeataServer的配置文件只需要配置application.yml 配置文件即可。
  • 从1.5.2版本开始支持Mysql8。

部署SeataServer

初始化数据库

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

Nacos配置

前往Nacos-配置管理界面操作。

  1. 添加配置service.vgroupMapping.default_tx_group

    Data ID: service.vgroupMapping.default_tx_group

    Group:SEATA_GROUP

    配置内容:default

  2. 添加配置 seataServer.properties

    Data ID:seataServer.properties

    Group:SEATA_GROUP

    配置内容:新手只需填写我 #中文注释的内容即可

    #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 #修改为线上IP:PORT
    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 #修改为线上IP:PORT
    store.db.user=root #修改
    store.db.password=root #修改
    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
    

创建 application.yml 配置文件

server:
  port: 7091

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

console:
  user:
    username: seata #seata-Web管理系统账号密码
    password: seata

seata:
  config:
    type: nacos
    nacos:
      server-addr: http://127.0.0.1:8848 #填线上Nacos的IP:PORT
      namespace: #命名空间,使用默认的不用填
      group: SEATA_GROUP #组
      username:
      password:
      data-id: seataServer.properties #seataServer配置文件
  registry:
    type: nacos
    nacos:
      application: seata-server #注册服务名称
      server-addr: http://127.0.0.1:8848 #填线上Nacos的IP:PORT
      group: SEATA_GROUP #组
      namespace: #命名空间,使用默认的不用填
      cluster: default
      username:
      password:
  store:
    mode: db
    db:
      datasource: druid
      db-type: mysql
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://127.0.0.1:3306/seata?serverTimezone=Asia/Shanghai #填线上Mysql的IP:PORT,seata数据库名,要和前面插入seata表同一个名
      user: root #数据库账号
      password: root #数据库密码
      min-conn: 5
      max-conn: 100
      global-table: global_table
      branch-table: branch_table
      lock-table: lock_table
      distributed-lock-table: distributed_lock
      query-limit: 100
      max-wait: 5000

  security:
    secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017
    tokenValidityInMilliseconds: 1800000
    ignore:
      urls: /,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/api/v1/auth/login

Docker下载

这里选择1.5.1版本

docker pull seataio/seata-server:1.5.1

启动seataServer

把前面创建的 application.yml 配置文件 复制到 /opt/seata/config/ 目录下(可以自己定义)

docker run --name seata-server \
        -p 8091:8091 \
        -p 7091:7091 \
        -e SEATA_IP=127.0.0.1 \ #这里填线上IP
        -e SEATA_PORT=8091 \
        -v /opt/seata/config/application.yml:/seata-server/resources/application.yml  \ #映射目录
        -d seataio/seata-server:1.5.1

完成

启动完成后,请求IP:7091即可,账号密码:seata

image-20220812162850636

客户端搭建

创建表-AT模式

在需要使用到分布式事务的服务数据库创建undo_log表。

-- 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 = utf8mb4 COMMENT ='AT transaction mode undo table';

添加POM依赖

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
    <version>2021.0.1.0</version>
    <!--需要排除低版本的seata,手动引入1.5.1-->
    <exclusions>
        <exclusion>
            <artifactId>seata-spring-boot-starter</artifactId>
            <groupId>io.seata</groupId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>io.seata</groupId>
    <artifactId>seata-spring-boot-starter</artifactId>
    <version>1.5.1</version>
</dependency>

客户端(user) 配置 application.yml 连接Seata

seata:
  enable: true
  application-id: seata-cilent-user
  tx-service-group: default_tx_group
  registry:
    type: nacos
    nacos:
      application: seata-server # seata 服务名
      # 非本地请修改具体的地址
      server-addr: http://127.0.0.1:8848
      group: SEATA_GROUP
  config:
    type: nacos
    nacos:
      # nacos ip地址
      server-addr: http://127.0.0.1:8848
      group: SEATA_GROUP
      data-id: "seataServer.properties"

客户端(order) 配置 application.yml 连接Seata

seata:
  enable: true
  application-id: seata-cilent-order
  tx-service-group: default_tx_group
  registry:
    type: nacos
    nacos:
      application: seata-server # seata 服务名
      # 非本地请修改具体的地址
      server-addr: http://127.0.0.1:8848
      group: SEATA_GROUP
  config:
    type: nacos
    nacos:
      # nacos ip地址
      server-addr: http://127.0.0.1:8848
      group: SEATA_GROUP
      data-id: "seataServer.properties"

测试

  1. 启动user服务
  2. 启动order服务
  3. 在order服务里面通过Feign调用user服务插入数据,模拟出现异常
  4. 加上注解:@GlobalTransactional(rollbackFor = Exception.class)

参考代码

@Transactional
@GlobalTransactional(rollbackFor = Exception.class)
public void insertOrder() {
    UserDTO userDTO = new UserDTO();
    userDTO.setUserName("admin");
    userDTO.setPassword("1234");
    marsUserClient.insert(userDTO); //这里调用user服务,插入一条数据
    Order order = new Order();
    order.setOrderNumber("998");
    this.save(order); //这里插入order服务数据
    int i = 1/0; //模拟发生异常
}

执行结果:回滚成功

image-20220812164716423

结语

Seata集成相比其他中间件更复杂,但是使用相对简单,只需要一个注解@GlobalTransactional即可。

  • 7
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
在Spring Cloud Alibaba使用Seata进行分布式事务,需要进行以下步骤: 1. 引入Seata依赖 在pom.xml文件中引入Seata的依赖: ``` <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-seata</artifactId> <version>2.2.0.RELEASE</version> </dependency> ``` 2. 配置Seata 在application.yml文件中配置Seata的相关参数,包括: - 服务端配置 ``` spring: cloud: alibaba: seata: tx-service-group: my_test_tx_group # Seata事务组名称 service: vgroup-mapping: my_test_tx_group: default # Seata服务组名称 group-id: default # Seata服务分组ID config: type: file # Seata配置类型 file: name: file.conf # Seata配置文件名称 path: /seata/config # Seata配置文件路径 ``` - 客户端配置 ``` mybatis: configuration: # 启用二级缓存 cache-enabled: true # 数据源配置 type-aliases-package: com.example.demo.entity mapper-locations: classpath:mapper/*.xml configuration-properties: # 自动驼峰转换 mapUnderscoreToCamelCase: true # 数据库连接池配置 druid: url: jdbc:mysql://localhost:3306/seata?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver # Seata配置 seata: enabled: true # 启用Seata application-id: seata-demo # 应用ID tx-service-group: my_test_tx_group # Seata事务组名称 service: vgroup-mapping: my_test_tx_group: default # Seata服务组名称 # 注册中心配置 registry: type: nacos # 注册中心类型 nacos: server-addr: localhost:8848 # 注册中心地址 namespace: public group: SEATA_GROUP file: name: file.conf # 注册中心配置文件名称 path: /seata/config # 注册中心配置文件路径 ``` 3. 配置数据源 在application.yml文件中配置数据源,包括: ``` spring: datasource: url: jdbc:mysql://localhost:3306/seata?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver ``` 4. 配置Seata代理数据源 在Spring Boot启动类中配置Seata代理数据源: ``` @SpringBootApplication @EnableDiscoveryClient @MapperScan("com.example.demo.mapper") @EnableFeignClients(basePackages = "com.example.demo.feign") @EnableTransactionManagement public class SeataDemoApplication { public static void main(String[] args) { SpringApplication.run(SeataDemoApplication.class, args); } @Bean @ConfigurationProperties(prefix = "spring.datasource") public DataSource dataSource() { return new DruidDataSource(); } @Bean public DataSourceProxy dataSourceProxy(DataSource dataSource) { return new DataSourceProxy(dataSource); } @Bean public GlobalTransactionScanner globalTransactionScanner() { return new GlobalTransactionScanner("seata-demo", "my_test_tx_group"); } } ``` 5. 编写业务代码 在业务代码中使用@GlobalTransactional注解标记需要参与分布式事务的方法,例如: ``` @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Autowired private OrderFeignClient orderFeignClient; @Override @GlobalTransactional public void createOrder(User user) { userMapper.insert(user); orderFeignClient.createOrder(user.getId()); } } ``` 以上就是在Spring Cloud Alibaba使用Seata进行分布式事务的步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值