一,前言
说到微服务,自然就少不了保证服务之间数据一致性的分布式事务,所以本篇就以Seata的AT模式如何在微服务的实际场景中应用进行实战说明,希望大家都能有个看其形知其意的效果。
1. 需求描述
会员提交订单,扣减商品库存,增加会员积分,完成前面步骤,更改订单状态为已完成。
根据需求可知这其中牵涉到订单、商品、会员3个微服务,分别对应 youlai-mall 商城项目的 mall-oms、mall-pms、mall-ums微服务。
2. 技术版本
3. 环境准备
3.1 Nacos安装和配置
https://www.cnblogs.com/haoxianrui/p/14059009.html
进入Nacos控制台,创建seata命名空间
记住命名空间ID自定义为seata_namespace_id,后面需要
3.2 Seata数据库创建
创建数据库名为seata,执行Seata的Github官方源码中提供的的MySQL数据库脚本
MySQL脚本地址:
https://github.com/seata/seata/blob/1.4.1/script/server/db/mysql.sql
二. seata-server安装
重点声明: 192.168.1.188 是安装Nacos和Seata的虚拟机IP
点击 Docker Hub链接 查看最新Seata版本
可以看到最新版本为1.4.1版本,复制指令获取最新版本镜像
docker pull seataio/seata-server:1.4.1
启动临时容器
docker run -d --name seata -p 8091:8091 seataio/seata-server
从临时容器获取到 registry.conf 配置文件
mkdir /opt/seata
docker cp seata:/seata-server/resources/registry.conf /opt/seata
修改registry.conf配置,类型选择nacos,namesapce为上文中在nacos新建的命名空间id即seata_namespace_id,精简如下:
vim /opt/seata/registry.conf
registry {
type = "nacos"
loadBalance = "RandomLoadBalance"
loadBalanceVirtualNodes = 10
nacos {
application = "seata-server"
serverAddr = "192.168.1.188:8848"
namespace = "seata_namespace_id"
group = "SEATA_GROUP"
cluster = "default"
}
}
config {
type = "nacos"
nacos {
serverAddr = "192.168.1.188:8848"
namespace = "seata_namespace_id"
group = "SEATA_GROUP"
}
}
安排好 registry.conf 之后,删除临时容器
docker rm -f seata
接下来着手开始推送Seata依赖配置至Nacos
从Seata的GitHub官方源码获取配置文件(config.txt)和推送脚本文件(nacos/nacos-config.sh)
地址:
因为脚本的关系,文件存放目录如下
/opt/seata
├── config.txt
└── nacos
└── nacos-config.sh
修改配置文件 config.txt
vim /opt/seata/config.txt
修改事务组和MySQL连接信息,修改信息如下:
service.vgroupMapping.mall_tx_group=default
store.mode=db
store.db.driverClassName=com.mysql.cj.jdbc.Driver
store.db.url=jdbc:mysql://www.youlai.store:3306/seata?useUnicode=true&rewriteBatchedStatements=true
store.db.user=root
store.db.password=123456
执行推送命令
cd /opt/seata/nacos
bash nacos-config.sh -h