分布式事务解决方案
什么是分布式事务,分布式事务解决方案详解(不清楚分布式事务的同学可以先看下这篇)
Seata下载地址
打开file.conf文件
搭建 自定义事务组名称+事务日志存储模式为db+数据库连接信息 1.修改file.conf的service模块-自定义事务组名称
名字随便取,什么都可以 .
2.修改file.conf的store模块-事务日志存储模式为db
改为db
自己配好数据库的信息! 不然后续启动会报错
3.建seata数据库和相关表
创建seata数据库,执行db_store.sql和undo_log文件建表文件
4.切换注册中心
conf下的registry.conf文件
切换为eureka并修改eureka配置
切换为自己的eureka地址.
启动eureka,并启动bin目录下的bat文件
启动成功如下图
eureka中可以看到Seata已经被注册进来
Seata AT 模式详解
参考此博文:Seata AT
创建四个服务Business,Storage,Order,Account.
Git地址:GitHub - jeespring/spring-cloud-seata
初始化订单、库存、账户三张表
DROP TABLE IF EXISTS `t_account`; CREATE TABLE `t_account` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `user_id` bigint(20) NOT NULL DEFAULT 0, `money` bigint(20) NOT NULL DEFAULT 0, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4; -- ---------------------------- -- Records of t_account -- ---------------------------- INSERT INTO `t_account` VALUES (1, 10001, 10000); -- ---------------------------- -- Table structure for t_order -- ---------------------------- DROP TABLE IF EXISTS `t_order`; CREATE TABLE `t_order` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `user_id` bigint(20) NOT NULL DEFAULT 0, `commodity_code` varchar(20) CHARACTER SET utf8mb4 NOT NULL DEFAULT '', `count` int(10) NOT NULL DEFAULT 0, `money` bigint(20) NOT NULL DEFAULT 0, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4; -- ---------------------------- -- Records of t_order -- ---------------------------- -- ---------------------------- -- Table structure for t_storage -- ---------------------------- DROP TABLE IF EXISTS `t_storage`; CREATE TABLE `t_storage` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `commodity_code` varchar(50) CHARACTER SET utf8mb4 NOT NULL DEFAULT '', `commodity_name` varchar(255) CHARACTER SET utf8mb4 NOT NULL DEFAULT '', `count` int(11) NOT NULL DEFAULT 0, `price` bigint(20) NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE, UNIQUE INDEX `commodity_code`(`commodity_code`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4; -- ---------------------------- -- Records of t_storage -- ---------------------------- INSERT INTO `t_storage` VALUES (1, '10001', '苹果手机', 100, 1000);
配置文件基本不变(Business不需要连接数据库,所以可以不配数据库)
依赖基本不变(Business不需要连接数据库,所以可以需要mybaties连接)
org.springframework.boot spring-boot-starterorg.springframework.boot spring-boot-starter-weborg.springframework.cloud spring-cloud-starter-netflix-eureka-clientorg.springframework.cloud spring-cloud-starter-loadbalancerorg.springframework.cloud spring-cloud-starter-openfeigncom.alibaba.cloud spring-cloud-starter-alibaba-seatacom.baomidou mybatis-plus-boot-startermysql mysql-connector-javaorg.springframework.boot spring-boot-starter-testtest
启动服务
主要业务逻辑
采购服务:Bussiness服务 开启@GlobalTransactional注解
仓储服务
帐户服务
订单服务
测试Seata中可以看到2109720215已经提交成功
服务中也可以看到相关log
异常测试
userid=10000直接异常
可以看到服务被Rollback
seata中可以看到事务被回滚
回滚的时候,是将之前保存的undo_log 取出来,进行数据恢复
参考博文大佬博文地址在此



