Seata

本文介绍了Seata分布式事务解决方案在SpringBoot中的应用,包括其组成部分(TC、TM、RM),如何下载和启动Seata服务,以及如何在SpringBoot项目中配置Seata与Druid数据源集成,以及在业务方法中启用全局事务和生成undo_log表的步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.概念

Seata 是一个开源的分布式事务解决方案,它为分布式系统提供ACID事务保障和一致性保证。

二.组成

  1. TC (Transaction Coordinator):事务协调器,负责全局事务的管理和协调,控制事务的提交与回滚。

  2. TM (Transaction Manager):事务管理器,负责定义事务的边界并管理分支事务的生命周期,包括事务的开始、提交和回滚等操作。

  3. RM (Resource Manager):资源管理器,负责与具体的数据源或资源进行交互,参与事务的操作,并根据 TM 的指令执行相应的提交或回滚操作。

三.使用

  • 下载:https://github.com/seata/seata/tags
  • 启动:seata-server.bat

四.整合到SpringBoot

1.导入依赖

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.9</version>
</dependency>

2.配置yaml

seata:
  enableAutoDataSourceProxy: false #关闭DataSource代理的自动配置,我们要手动配置
spring:
  cloud:
    alibaba:
      seata:
        tx-service-group: fsp_tx_group #这里和file.conf中事务组名一样

3.拷贝配置

1.resources/file.conf

transport {
  # tcp udt unix-domain-socket
  type = "TCP"
  #NIO NATIVE
  server = "NIO"
  #enable heartbeat
  heartbeat = true
  # the client batch send request enable
  enableClientBatchSendRequest = true
  #thread factory for netty
  threadFactory {
    bossThreadPrefix = "NettyBoss"
    workerThreadPrefix = "NettyServerNIOWorker"
    serverExecutorThread-prefix = "NettyServerBizHandler"
    shareBossWorker = false
    clientSelectorThreadPrefix = "NettyClientSelector"
    clientSelectorThreadSize = 1
    clientWorkerThreadPrefix = "NettyClientWorkerThread"
    # netty boss thread size,will not be used for UDT
    bossThreadSize = 1
    #auto default pin or 8
    workerThreadSize = "default"
  }
  shutdown {
    # when destroy server, wait seconds
    wait = 3
  }
  serialization = "seata"
  compressor = "none"
}
service {
  #transaction service group mapping
  vgroupMapping.fsp_tx_group = "default"
  #only support when registry.type=file, please don't set multiple addresses
  default.grouplist = "127.0.0.1:8091"
  #degrade, current not support
  enableDegrade = false
  #disable seata
  disableGlobalTransaction = false
}

client {
  rm {
    asyncCommitBufferLimit = 10000
    lock {
      retryInterval = 10
      retryTimes = 30
      retryPolicyBranchRollbackOnConflict = true
    }
    reportRetryCount = 5
    tableMetaCheckEnable = false
    reportSuccessEnable = false
  }
  tm {
    commitRetryCount = 5
    rollbackRetryCount = 5
  }
  undo {
    dataValidation = true
    logSerialization = "jackson"
    logTable = "undo_log"
  }
  log {
    exceptionRate = 100
  }
}

2.resources/registry.conf

registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "file"

  nacos {
    serverAddr = "localhost"
    namespace = ""
    cluster = "default"
  }
  eureka {
    serviceUrl = "http://localhost:8761/eureka"
    application = "default"
    weight = "1"
  }
  redis {
    serverAddr = "localhost:6379"
    db = "0"
    password = ""
    cluster = "default"
    timeout = "0"
  }
  zk {
    cluster = "default"
    serverAddr = "127.0.0.1:2181"
    session.timeout = 6000
    connect.timeout = 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、springCloudConfig
  type = "file"

  nacos {
    serverAddr = "localhost"
    namespace = ""
    group = "SEATA_GROUP"
  }
  consul {
    serverAddr = "127.0.0.1:8500"
  }
  apollo {
    app.id = "seata-server"
    apollo.meta = "http://192.168.1.204:8801"
    namespace = "application"
  }
  zk {
    serverAddr = "127.0.0.1:2181"
    session.timeout = 6000
    connect.timeout = 2000
    username = ""
    password = ""
  }
  etcd3 {
    serverAddr = "http://localhost:2379"
  }
  file {
    name = "file.conf"
  }
}

4.DataSource配置

1.排除DataSource自动配置
在启动类上修改@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class})
2.把DataSource交给Seata代理
MybatisPlus版本


import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import io.seata.rm.datasource.DataSourceProxy;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

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

    //mapper.xml路径
    @Value("${mybatis-plus.mapper-locations}")
    private String mapperLocations;

    //手动配置bean
    @Bean
    @ConfigurationProperties("spring.datasource")
    public DataSource druidDataSource(){
        return new DruidDataSource();
    }

    @Bean
    public MybatisSqlSessionFactoryBean sqlSessionFactoryBean(DataSourceProxy dataSourceProxy) throws Exception {
        //处理MybatisPlus
        MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean();
        factory.setDataSource(dataSourceProxy);
        factory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
        //事务管理工厂
        factory.setTransactionFactory(new SpringManagedTransactionFactory());
        return factory;
    }

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

}

Mybatis版本

import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

//使用seata对DataSource进行代理
@Configuration
public class DataSourceProxyConfig {

    //mapper.xml路径
    @Value("${mybatis.mapper-locations}")
    private String mapperLocations;

    //手动配置bean
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource(){
        return new DruidDataSource();
    }

    @Bean
    public SqlSessionFactory sessionFactory(DataSourceProxy dataSourceProxy) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSourceProxy);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
        //事务管理工厂
        sessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
        return sessionFactoryBean.getObject();
    }

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

5.业务方法

方法上贴 : @GlobalTransactional(rollbackFor = Exception.class) 开启Seata全局事务
注:只需要在入口方法上加上该注解

6.注释事务开启注解

注意:不能加@EnableTransactionManagement 注解了 , 也不需要加@Transactional

7.生成undolog表

-- 注意此处0.3.0+ 增加唯一索引 ux_undo_log
CREATE TABLE `undo_log` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `branch_id` bigint(20) NOT NULL,
  `xid` varchar(100) NOT NULL,
  `context` varchar(128) NOT NULL,
  `rollback_info` longblob NOT NULL,
  `log_status` int(11) NOT NULL,
  `log_created` datetime NOT NULL,
  `log_modified` datetime NOT NULL,
  `ext` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
### Seata 分布式事务框架介绍 Seata 是一款开源的分布式事务解决方案,致力于提供高性能和简单易用的分布式事务服务[^3]。它融合了阿里巴巴和蚂蚁金服在分布式事务技术上的积累,并沉淀了新零售、云计算和新金融等场景下丰富的实践经验[^1]。Seata 提供了多种事务模式,包括 AT 模式(推荐)、TCC 模式、SAGA 模式和 XA 模式,为用户打造了一站式的分布式事务解决方案。 通过合理配置和优化,Seata 能够有效解决分布式系统的事务一致性问题,适用于电商、金融、物流等多种业务场景。实际使用时应根据业务特点选择合适的模式,配合完善的监控体系和运维方案,保证系统的高可用性和数据一致性[^2]。 --- ### Seata 分布式事务框架的使用步骤 #### 1. 引入依赖 在项目中引入 Seata 的相关依赖。以下是一个 Maven 项目的依赖示例: ```xml <dependency> <groupId>io.seata</groupId> <artifactId>seata-spring-boot-starter</artifactId> <version>1.5.0</version> <!-- 根据需要选择版本 --> </dependency> ``` #### 2. 配置事务切面和数据源代理 在 Spring Boot 项目中,取消默认的数据源自动创建,改为使用自定义的数据源,并配置事务切面。以下是主启动类的代码示例: ```java package cn.kt.springcloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication(exclude = DataSourceAutoConfiguration.class) @EnableDiscoveryClient @EnableFeignClients public class SeataOrderMainApp2001 { public static void main(String[] args) { SpringApplication.run(SeataOrderMainApp2001.class, args); } } ``` #### 3. 添加 `@GlobalTransactional` 注解 在需要开启分布式事务的业务方法上添加 `@GlobalTransactional` 注解。例如: ```java import io.seata.spring.annotation.GlobalTransactional; @Service public class OrderService { @Autowired private OrderMapper orderMapper; @GlobalTransactional public void createOrder(Order order) { // 执行订单创建逻辑 orderMapper.insert(order); // 假设调用其他微服务完成支付 paymentService.pay(order.getOrderId(), order.getAmount()); } } ``` #### 4. 配置文件 在 `application.yml` 或 `application.properties` 文件中,配置 Seata 的相关参数。以下是一个简单的配置示例: ```yaml spring: cloud: alibaba: seata: tx-service-group: my_tx_group # 定义事务组名称 seata: enabled: true service: vgroup-mapping: my_tx_group: default # 映射事务组到具体的事务管理器 grouplist: default: 127.0.0.1:8091 # Seata Server 地址 ``` --- ### Seata 的核心概念与原理 #### 1. 三大角色 Seata 的三大核心角色分别为 TM(Transaction Manager)、RM(Resource Manager)和 TC(Transaction Coordinator)[^3]: - **TM**:事务管理器,负责协调整个分布式事务的提交或回滚。 - **RM**:资源管理器,负责管理本地资源(如数据库连接),并将其注册到 TC 中。 - **TC**:事务协调器,作为独立的服务运行,负责维护全局事务的状态并驱动事务的提交或回滚。 #### 2. AT 模式 AT 模式是 Seata 推荐使用的事务模式,具有高效性和易用性。其主要特点如下: - **一阶段提交**:执行业务 SQL 并生成 Undo Log。 - **二阶段提交**:根据全局事务的状态决定提交或回滚。回滚时通过 Undo Log 还原数据状态[^5]。 --- ### 示例代码 以下是一个完整的 Seata 使用示例: #### 主启动类 ```java package com.example.seata; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication(exclude = DataSourceAutoConfiguration.class) @EnableDiscoveryClient public class SeataDemoApplication { public static void main(String[] args) { SpringApplication.run(SeataDemoApplication.class, args); } } ``` #### 数据源配置 ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/seata_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver ``` #### 业务服务类 ```java import io.seata.spring.annotation.GlobalTransactional; @Service public class OrderService { @Autowired private OrderMapper orderMapper; @Autowired private PaymentService paymentService; @GlobalTransactional public void placeOrder(Order order) { // 创建订单 orderMapper.insert(order); // 调用支付服务 paymentService.pay(order.getOrderId(), order.getAmount()); } } ``` --- ### 注意事项 1. 确保 Seata Server 已经正确部署并运行。 2. 配置好 Undo Log 表结构,Seata 默认会自动创建 Undo Log 表。 3. 根据业务需求选择合适的事务模式,例如 AT 模式适合大多数场景,而 TCC 模式适合对性能要求较高的场景。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值