springcloud 实现seata 分布式事务
时间: 2025-09-09 19:11:45 AIGC 浏览: 11
在 Spring Cloud 微服务架构中,实现分布式事务是一个常见需求。Seata 是一个开源的分布式事务解决方案,它提供了高性能且简单易用的分布式事务服务。
下面将详细说明如何在 Spring Cloud 中集成 Seata,实现分布式事务。
---
## ✅ 一、环境准备
### 1. 技术栈要求
| 技术 | 版本建议 |
|------|----------|
| Spring Boot | 2.6.x ~ 2.7.x |
| Spring Cloud | 2021.x |
| Spring Cloud Alibaba | 2021.x.x |
| Seata | 1.6.x |
| Nacos | 2.0.x |
| 数据库 | MySQL 5.7+ |
---
## ✅ 二、Seata 架构简介
Seata 支持多种事务模式,最常用的是 **AT 模式(Auto Transaction)**,它通过拦截数据库操作,实现事务的自动提交和回滚。
Seata 的核心组件:
- **TC(Transaction Coordinator)**:事务协调器,即 Seata Server。
- **TM(Transaction Manager)**:事务管理器,负责全局事务的开启、提交或回滚。
- **RM(Resource Manager)**:资源管理器,负责分支事务的注册和提交。
---
## ✅ 三、搭建 Seata Server
### 1. 下载 Seata Server
从官网下载:[https://github.com/seata/seata/releases](https://github.com/seata/seata/releases)
选择 `seata-server-xxx.zip` 解压。
### 2. 修改配置文件
进入 `conf/file.conf`,修改事务日志存储方式(推荐使用 `file` 或 `db`):
```properties
store.mode = file
```
或使用数据库:
```properties
store.mode = db
store.db.datasource = druid
store.db.dbType = mysql
store.db.url = jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true&rewriteBatchedStatements=true
store.db.user = root
store.db.password = root
```
### 3. 启动 Seata Server
```bash
sh seata-server.sh -p 8091 -h 127.0.0.1 -m file
```
---
## ✅ 四、Spring Cloud 微服务集成 Seata
### 1. 引入依赖(Maven)
```xml
<!-- Seata Starter -->
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
<version>1.6.1</version>
</dependency>
<!-- Nacos Discovery -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- Feign Client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
```
### 2. 配置 Seata(application.yml)
```yaml
seata:
enabled: true
application-id: order-service
tx-service-group: my_test_tx_group
service:
vgroup-mapping:
my_test_tx_group: default
grouplist:
default: 127.0.0.1:8091
config:
type: file
registry:
type: nacos
nacos:
server-addr: 127.0.0.1:8848
application: seata-server
```
### 3. 启用 Seata(主类上加注解)
```java
@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
```
---
## ✅ 五、使用 Seata 实现分布式事务
### 1. 定义 Feign Client
```java
@FeignClient(name = "account-service")
public interface AccountClient {
@PostMapping("/account/deduct")
void deduct(@RequestBody BigDecimal money);
}
```
### 2. 使用 `@GlobalTransactional` 注解开启分布式事务
```java
@Service
public class OrderService {
@Autowired
private AccountClient accountClient;
@Autowired
private OrderMapper orderMapper;
@GlobalTransactional
public void createOrder(BigDecimal money) {
// 1. 扣减账户余额
accountClient.deduct(money);
// 2. 创建订单
Order order = new Order();
order.setMoney(money);
order.setStatus("CREATED");
orderMapper.insert(order);
// 模拟异常,触发回滚
if (money.compareTo(BigDecimal.ZERO) > 0) {
throw new RuntimeException("模拟业务异常");
}
}
}
```
---
## ✅ 六、数据库配置(Seata AT 模式要求)
### 1. 添加 `undo_log` 表(每个参与事务的数据库都要加)
```sql
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;
```
### 2. 使用 Seata 数据源代理(可选)
```yaml
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/order_db?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
type: io.seata.rm.datasource.SeataDataSourceProxy
```
---
## ✅ 七、测试分布式事务
1. 启动 Seata Server。
2. 启动 Nacos Server。
3. 启动多个微服务(如 order-service、account-service)。
4. 调用接口,模拟异常,观察事务是否回滚。
---
## ✅ 八、总结
| 模块 | 说明 |
|------|------|
| Seata Server | 作为 TC,协调分布式事务 |
| Feign Client | 作为 RM,注册分支事务 |
| `@GlobalTransactional` | 作为 TM,开启全局事务 |
| `undo_log` 表 | 记录事务日志,用于回滚 |
---
###
阅读全文
相关推荐

















