seata学习笔记(一)——springcloud集成seata
2021-05-26 本文已影响0人
那些年搬过的砖
便于简单展示,只配置了两个服务之间,用于验证seata分布式事务
seata server启动
从seata官网下载seata server包,包中自带了bat和sh启动脚本,注册方式修改为eureka(registry.conf)
registry {
# file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
type = "eureka"
nacos {
application = "seata-server"
serverAddr = "localhost"
namespace = ""
cluster = "default"
username = ""
password = ""
}
eureka {
serviceUrl = "http://localhost:8761/eureka"
application = "default"
weight = "1"
}
...
完成注册
整体项目结构
order服务引入seata及seata配置
pom.xml
<!-- seata -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-seata</artifactId>
<version>2.2.0.RELEASE</version>
<exclusions>
<exclusion>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
application.yml
# seata配置
seata:
enabled: true
application-id: order-seata
tx-service-group: cloud-web_tx_group
registry:
type: eureka
eureka:
service-url: http://${eureka.host:localhost}:${eureka.port:8761}/eureka/
service:
vgroup-mapping:
cloud-web_tx_group: default
GlobalTransactional配置全局事务
/**
* 模拟下单操作,验证分布式事务
* @param id
* @return
*/
@GlobalTransactional
@GetMapping("/{id}/add")
public void add(@PathVariable Integer id) {
orderService.add(id);
}
add接口中模拟分布式事务,
@Override
public void add(Integer userId) {
//新增一条订单记录
Order order = new Order();
order.setUserId(1);
order.setProductId(1);
order.setPayAmount(1D);
order.setStatus("1");
order.setAddTime(new Date());
order.setLastUpdateTime(new Date());
this.save(order);
//更新账户信息,模拟分布式事务
accountFeignService.updateAccount(userId);
}