分布式事务框架seata快速入门-seata的搭建(一)
分布式事务框架seata快速入门-seata的使用(二)
本系列源码地址 ,业务脚本位置:
1. 引入依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
</dependency>
2. 配置
bootstrap.yml加入以下配置
seata:
enabled: true
service:
#business-service为分组,配置项值为TC集群名
vgroup-mapping:
business-service: default
grouplist:
#seata服务地址
default: xx.xx.x.135:8091
disable-global-transaction: false
具体配置参照seata配置
3. 业务数据库中创建回滚日志表
CREATE TABLE `undo_log` (
`branch_id` bigint(20) NOT NULL COMMENT 'branch transaction id',
`xid` varchar(128) 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 DEFAULT CHARSET=utf8 COMMENT='AT transaction mode undo table';
4. 实战代码
@GlobalTransactional(timeoutMills = 300000, name = "order-tx")
public String createOrder(double orderPrice) {
log.info("====== order Service Begin ... xid: " + RootContext.getXID());
//订单入库
OrderEntity orderEntity = new OrderEntity();
orderEntity.setOrderSn(UUID.randomUUID().toString().replace("-",""));
long time = System.currentTimeMillis();
orderEntity.setCreateTime(time);
orderEntity.setUpdateTime(time);
orderEntity.setAmount(orderPrice);
orderMapper.insert(orderEntity);
String res = "订单创建成功,订单总价为" + orderPrice + "(元)";
//发货
String address = "西安市";
boolean shipFlag = shipRemote.shipOrder(address);
res += ",现在进行发货,发货地址为:"+address+",发货成功状态为:"+shipFlag;
//送会员
Boolean present = memberRemote.present("张三");
res += ",现在为期赠送会员,赠送结果成功状态为:" + present;
return res;
}
注意
所有的事务方法都要添加本地事务注解
@Transactional
,seata依赖本地事务的回滚