date
Jul 7, 2022
type
Page
status
Invisible
slug
distributed-transactions-seata
summary
概要:1 Seata服务安装;2 项目集成Seata;3 分布式事务案例演示
tags
微服务
spring-cloud-alibaba
商城
category
商城实战
password
Property
Sep 27, 2022 02:57 AM
icon
SEATA
分布式事务解决方案seata
一、Seata服务的安装
我们可以先导入Seata的依赖,根据依赖的版本来下载对应的Seata安装文件
下载后解压缩然后进入conf文件夹,然后通过registery.conf文件可以更新配置中心和注册中心的信息。
然后进入 bin 目录 通过 seata-server.bat文件来启动服务
然后进入nacos注册中心可以看到对应的服务,表示OK
二、项目集成Seata
接下来看看如何在商城项目中来集成Seata,首先是file.conf文件
1. 网络传输配置:
transport { # tcp udt unix-domain-socket type = "TCP" #NIO NATIVE server = "NIO" #enable heartbeat heartbeat = true #thread factory for netty thread-factory { boss-thread-prefix = "NettyBoss" worker-thread-prefix = "NettyServerNIOWorker" server-executor-thread-prefix = "NettyServerBizHandler" share-boss-worker = false client-selector-thread-prefix = "NettyClientSelector" client-selector-thread-size = 1 client-worker-thread-prefix = "NettyClientWorkerThread" # netty boss thread size,will not be used for UDT boss-thread-size = 1 #auto default pin or 8 worker-thread-size = 8 } }
2. 事务日志存储配置:
该部分配置仅在seata-server中使用,如果选择db请配合seata.sql使用
## transaction log store, only used in seata-server store { ## store mode: file、db mode = "file" ## file store property file { ## store location dir dir = "sessionStore" } ## database store property db { ## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp) etc. datasource = "dbcp" ## mysql/oracle/h2/oceanbase etc. db-type = "mysql" driver-class-name = "com.mysql.jdbc.Driver" url = "jdbc:mysql://127.0.0.1:3306/seata" user = "mysql" password = "mysql" } }
3. 当前微服务在Seata服务器中注册的信息配置:
service { # 事务分组,默认:${spring.applicaiton.name}-fescar-service-group,可以随便写 vgroup_mapping.${spring.application.name}-fescar-service-group = "default" # 仅支持单节点,不要配置多地址,这里的default要和事务分组的值一致 default.grouplist = "127.0.0.1:8091" #seata-server服务器地址,默认是8091 # 降级,当前不支持 enableDegrade = false # 禁用全局事务 disableGlobalTransaction = false }
4. 客户端相关工作的机制
client { rm { async.commit.buffer.limit = 10000 lock { retry.internal = 10 retry.times = 30 retry.policy.branch-rollback-on-conflict = true } report.retry.count = 5 table.meta.check.enable = false report.success.enable = true } tm { commit.retry.count = 5 rollback.retry.count = 5 } undo { data.validation = true log.serialization = "jackson" log.table = "undo_log" } log { exceptionRate = 100 } support { # auto proxy the DataSource bean spring.datasource.autoproxy = false } }
首先我们需要把registry.conf和file.conf两个配置文件拷贝到对应的项目的属性文件目录中
然后我们在属性文件中定义 tx-service-group 信息
然后在file.conf中添加service属性,然后关联刚刚设置的tx-service-group信息。注意1.1版本后属性更新为了驼峰命名法:
三、案例演示
我们在下订单的操作中除了已有的生成订单和订单项已经锁定库存操作外我们还显示的增加的了一个会有积分调整的服务。[1/0],这样一来如果锁定库存成功,但是会员积分调整失败,被分布式事务管理的逻辑中,锁库存的操作会回滚。