最全Java微服务分布式事务框架seata(1),2024年最新面试被逆袭是什么感觉

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

    "beforeImage": {
        "rows": [{
            "fields": [{
                "name": "id",
                "type": 4,
                "value": 1
            }, {
                "name": "name",
                "type": 12,
                "value": "TXC"
            }, {
                "name": "since",
                "type": 12,
                "value": "2014"
            }]
            
        }],
        "tableName": "product"
    },
    "sqlType": "UPDATE"
}],
"xid": "xid:xxx"

}



> 
> 
> > 
> > 提交前,向 TC 注册分支:申请  
> >  product 表中,主键值等于 1 的记录的 全局锁 。
> > 
> > 
> > 
> 
> 
> 



> 
> 
> > 
> > 本地事务提交:业务数据的更新和前面步骤中生成的 UNDO LOG 一并提交。
> > 
> > 
> > 
> 
> 
> 



> 
> 
> > 
> > 将本地事务提交的结果上报给 TC。
> > 
> > 
> > 
> 
> 
> 


#### 2.5.2、 二阶段-回滚



> 
> 
> > 
> > 收到 TC 的分支回滚请求,开启一个本地事务,执行如下操作。
> > 
> > 
> > 
> 
> 
> 



> 
> 
> > 
> > 通过 XID 和 Branch ID 查找到相应的 UNDO LOG 记录。
> > 
> > 
> > 
> 
> 
> 



> 
> 
> > 
> > 数据校验:拿 UNDO LOG 中的后镜与当前数据进行比较,如果有不同,说明数据被当前全局事务之外的动作做了修改。这种情况,需要根据配置策略来做处理,详细的说明在另外的文档中介绍。
> > 
> > 
> > 
> 
> 
> 



> 
> 
> > 
> > 根据 UNDO LOG 中的前镜像和业务 SQL 的相关信息生成并执行回滚的语句:
> > 
> > 
> > 
> 
> 
> 



update product set name = ‘TXC’ where id = 1;



> 
> 
> > 
> > 提交本地事务。并把本地事务的执行结果(即分支事务回滚的结果)上报给 TC。
> > 
> > 
> > 
> 
> 
> 


#### 2.5.3、二阶段-提交



> 
> 
> > 
> > 收到 TC 的分支提交请求,把请求放入一个异步任务的队列中,马上返回提交成功的结果给 TC。
> > 
> > 
> > 
> 
> 
> 



> 
> 
> > 
> > 异步任务阶段的分支提交请求将异步和批量地删除相应 UNDO LOG 记录。
> > 
> > 
> > 
> 
> 
> 


## 3、spring cloud 与seata整合


![在这里插入图片描述](https://img-blog.csdnimg.cn/265fb21282524800bf7f842fa17fba71.png)


### 3.1、seata配置


下载地址:https://github.com/seata/seata/releases/download/v1.4.2/seata-server-1.4.2.zip  
 **解压到D盘**


#### 3.1.1、修改配置文件


##### 3.1.1.1、conf/file.conf 修改成db模式



transaction log store, only used in seata-server

store {

store mode: file、db、redis

mode = “db”

rsa decryption public key

publicKey = “”

file store property

file {
## store location dir
dir = “sessionStore”
# branch session size , if exceeded first try compress lockkey, still exceeded throws exceptions
maxBranchSessionSize = 16384
# globe session size , if exceeded throws exceptions
maxGlobalSessionSize = 512
# file buffer size , if exceeded allocate new buffer
fileWriteBufferCacheSize = 16384
# when recover batch read size
sessionReloadReadSize = 100
# async, sync
flushDiskMode = async
}

database store property

db {
## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp)/HikariDataSource(hikari) etc.
datasource = “druid”
## mysql/oracle/postgresql/h2/oceanbase etc.
dbType = “mysql”
driverClassName = “com.mysql.jdbc.Driver”
## if using mysql to store the data, recommend add rewriteBatchedStatements=true in jdbc connection param
url = “jdbc:mysql://127.0.0.1:3306/seata?rewriteBatchedStatements=true”
user = “root”
password = “root”
minConn = 5
maxConn = 100
globalTable = “global_table”
branchTable = “branch_table”
lockTable = “lock_table”
queryLimit = 100
maxWait = 5000
}

redis store property

redis {
## redis mode: single、sentinel
mode = “single”
## single mode property
single {
host = “127.0.0.1”
port = “6379”
}
## sentinel mode property
sentinel {
masterName = “”
## such as “10.28.235.65:26379,10.28.235.65:26380,10.28.235.65:26381”
sentinelHosts = “”
}
password = “”
database = “0”
minConn = 1
maxConn = 10
maxTotal = 100
queryLimit = 100
}
}


##### 3.1.1.2、conf/registry.conf



registry {

file 、nacos 、eureka、redis、zk、consul、etcd3、sofa

type = “nacos”

nacos {
application = “seata-server”
serverAddr = “127.0.0.1:8848”
group = “SEATA_GROUP”
namespace = “1ff3782d-b62d-402f-8bc4-ebcf40254d0a”
cluster = “default”
username = “nacos”
password = “nacos”
}
eureka {
serviceUrl = “http://localhost:8761/eureka”
application = “default”
weight = “1”
}
redis {
serverAddr = “localhost:6379”
db = 0
password = “”
cluster = “default”
timeout = 0
}
zk {
cluster = “default”
serverAddr = “127.0.0.1:2181”
sessionTimeout = 6000
connectTimeout = 2000
username = “”
password = “”
}
consul {
cluster = “default”
serverAddr = “127.0.0.1:8500”
aclToken = “”
}
etcd3 {
cluster = “default”
serverAddr = “http://localhost:2379”
}
sofa {
serverAddr = “127.0.0.1:9603”
application = “default”
region = “DEFAULT_ZONE”
datacenter = “DefaultDataCenter”
cluster = “default”
group = “SEATA_GROUP”
addressWaitTime = “3000”
}
file {
name = “file.conf”
}
}

config {

file、nacos 、apollo、zk、consul、etcd3

type = “file”

nacos {
serverAddr = “127.0.0.1:8848”
namespace = “”
group = “SEATA_GROUP”
username = “nacos”
password = “nacos”
dataId = “seataServer.properties”
}
consul {
serverAddr = “127.0.0.1:8500”
aclToken = “”
}
apollo {
appId = “seata-server”
## apolloConfigService will cover apolloMeta
apolloMeta = “http://192.168.1.204:8801”
apolloConfigService = “http://192.168.1.204:8080”
namespace = “application”
apolloAccesskeySecret = “”
cluster = “seata”
}
zk {
serverAddr = “127.0.0.1:2181”
sessionTimeout = 6000
connectTimeout = 2000
username = “”
password = “”
nodePath = “/seata/seata.properties”
}
etcd3 {
serverAddr = “http://localhost:2379”
}
file {
name = “file.conf”
}
}


**注意:nacos命名空间namespace定义成自己的。**


##### 3.1.1.3、下载config.tex


https://github.com/seata/seata/tree/develop/script/config-center/config.text 保存到seata根目录,文件名config.txt



#For details about configuration items, see https://seata.io/zh-cn/docs/user/configurations.html
#Transport configuration, for client and server
transport.type=TCP
transport.server=NIO
transport.heartbeat=true
transport.enableTmClientBatchSendRequest=false
transport.enableRmClientBatchSendRequest=true
transport.enableTcServerBatchSendResponse=false
transport.rpcRmRequestTimeout=30000
transport.rpcTmRequestTimeout=30000
transport.rpcTcRequestTimeout=30000
transport.threadFactory.bossThreadPrefix=NettyBoss
transport.threadFactory.workerThreadPrefix=NettyServerNIOWorker
transport.threadFactory.serverExecutorThreadPrefix=NettyServerBizHandler
transport.threadFactory.shareBossWorker=false
transport.threadFactory.clientSelectorThreadPrefix=NettyClientSelector
transport.threadFactory.clientSelectorThreadSize=1
transport.threadFactory.clientWorkerThreadPrefix=NettyClientWorkerThread
transport.threadFactory.bossThreadSize=1
transport.threadFactory.workerThreadSize=default
transport.shutdown.wait=3
transport.serialization=seata
transport.compressor=none
#Transaction routing rules configuration, only for the client
service.vgroupMapping.default_tx_group=default
#If you use a registry, you can ignore it
service.default.grouplist=127.0.0.1:8091
service.enableDegrade=false
service.disableGlobalTransaction=false
#Transaction rule configuration, only for the client
client.rm.asyncCommitBufferLimit=10000
client.rm.lock.retryInterval=10
client.rm.lock.retryTimes=30
client.rm.lock.retryPolicyBranchRollbackOnConflict=true
client.rm.reportRetryCount=5
client.rm.tableMetaCheckEnable=true
client.rm.tableMetaCheckerInterval=60000
client.rm.sqlParserType=druid
client.rm.reportSuccessEnable=false
client.rm.sagaBranchRegisterEnable=false
client.rm.sagaJsonParser=fastjson
client.rm.tccActionInterceptorOrder=-2147482648
client.tm.commitRetryCount=5
client.tm.rollbackRetryCount=5
client.tm.defaultGlobalTransactionTimeout=60000
client.tm.degradeCheck=false
client.tm.degradeCheckAllowTimes=10
client.tm.degradeCheckPeriod=2000
client.tm.interceptorOrder=-2147482648
client.undo.dataValidation=true
client.undo.logSerialization=jackson
client.undo.onlyCareUpdateColumns=true
server.undo.logSaveDays=7
server.undo.logDeletePeriod=86400000
client.undo.logTable=undo_log
client.undo.compress.enable=true
client.undo.compress.type=zip
client.undo.compress.threshold=64k
#For TCC transaction mode
tcc.fence.logTableName=tcc_fence_log
tcc.fence.cleanPeriod=1h
#Log rule configuration, for client and server
log.exceptionRate=100
#Transaction storage configuration, only for the server. The file, db, and redis configuration values are optional.
store.mode=db
store.lock.mode=db
store.session.mode=db
#Used for password encryption
store.publicKey=
#If store.mode,store.lock.mode,store.session.mode are not equal to file, you can remove the configuration block.
store.file.dir=file_store/data
store.file.maxBranchSessionSize=16384
store.file.maxGlobalSessionSize=512
store.file.fileWriteBufferCacheSize=16384
store.file.flushDiskMode=async
store.file.sessionReloadReadSize=100
#These configurations are required if the store mode is db. If store.mode,store.lock.mode,store.session.mode are not equal to db, you can remove the configuration block.
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.jdbc.Driver
store.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true&rewriteBatchedStatements=true
store.db.user=root
store.db.password=root
store.db.minConn=5
store.db.maxConn=30
store.db.globalTable=global_table
store.db.branchTable=branch_table
store.db.distributedLockTable=distributed_lock
store.db.queryLimit=100
store.db.lockTable=lock_table
store.db.maxWait=5000
#These configurations are required if the store mode is redis. If store.mode,store.lock.mode,store.session.mode are not equal to redis, you can remove the configuration block.
store.redis.mode=single
store.redis.single.host=127.0.0.1
store.redis.single.port=6379
store.redis.sentinel.masterName=
store.redis.sentinel.sentinelHosts=
store.redis.maxConn=10
store.redis.minConn=1
store.redis.maxTotal=100
store.redis.database=0
store.redis.password=
store.redis.queryLimit=100
#Transaction rule configuration, only for the server
server.recovery.committingRetryPeriod=1000
server.recovery.asynCommittingRetryPeriod=1000
server.recovery.rollbackingRetryPeriod=1000
server.recovery.timeoutRetryPeriod=1000
server.maxCommitRetryTimeout=-1
server.maxRollbackRetryTimeout=-1
server.rollbackRetryTimeoutUnlockEnable=false
server.distributedLockExpireTime=10000
server.xaerNotaRetryTimeout=60000
server.session.branchAsyncQueueSize=5000
server.session.enableBranchAsyncRemove=false
server.enableParallelRequestHandle=false
#Metrics configuration, only for the server
metrics.enabled=false
metrics.registryType=compact
metrics.exporterList=prometheus
metrics.exporterPrometheusPort=9898


##### 3.1.1.4、下载nacos-config.sh到conf


然后执行命令:sh nacos-config.sh -h localhost -p 8848 -g SEATA\_GROUP -t 1ff3782d-b62d-402f-8bc4-ebcf40254d0a -u nacos -w nacos  
 把seata配置同步到nacos  
 ![在这里插入图片描述](https://img-blog.csdnimg.cn/125ddf92ed6f44f584370bd041d64f2b.png)


#### 3.1.2、导入数据库


创建数据库:create database seata;  
 然后执行以下的脚本。  
 https://github.com/seata/seata/blob/2.x/script/server/db/mysql.sql  
 global\_table: 全局事务表,每当有一个全局事务发起后,就会在该表中记录全局事务的ID  
 branch\_table: 分支事务表,记录每一个分支事务的 ID,分支事务操作的哪个数据库等信息  
 lock\_table: 全局锁


#### 3.1.3、启动seata server


D:\seata\seata-server-1.4.2\bin\seata-server.bat


### 3.2、用例


用户购买商品的业务逻辑。整个业务逻辑由3个微服务提供支持:


* 仓储服务:对给定的商品扣除仓储数量。
* 订单服务:根据采购需求创建订单。
* 帐户服务:从用户帐户中扣除余额。  
 ![在这里插入图片描述](https://img-blog.csdnimg.cn/126a6ef02df3445c86d52f4a1b85a914.png)  
 解决方案:  
 ![在这里插入图片描述](https://img-blog.csdnimg.cn/5d5212a8d2bb46908dc25e939a7bc779.png)


#### 3.2.1、项目配置


##### 3.2.1.1、创建四个服务


order-service(对应order数据库)  
 account-service(对应account数据库)  
 storage-service(对应storage数据库)  
 business-service


##### 3.2.1.2、每个业务数据库增加回滚表



CREATE TABLE undo\_log (
id bigint(20) NOT NULL AUTO_INCREMENT,
branch\_id bigint(20) NOT NULL,
xid varchar(100) NOT NULL,
context varchar(128) NOT NULL,
rollback\_info longblob NOT NULL,
log\_status int(11) NOT NULL,
log\_created datetime NOT NULL,
log\_modified datetime NOT NULL,
ext varchar(100) DEFAULT NULL,
PRIMARY KEY (id),
UNIQUE KEY ux\_undo\_log (xid,branch\_id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;


##### 3.2.1.3、执行业务表脚本



USE storage;
DROP TABLE IF EXISTS storage\_tbl;
CREATE TABLE storage\_tbl (
id int(11) NOT NULL AUTO_INCREMENT,
commodity\_code varchar(255) DEFAULT NULL,
count int(11) DEFAULT 0,
PRIMARY KEY (id),
UNIQUE KEY (commodity\_code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

USE order;
DROP TABLE IF EXISTS order\_tbl;
CREATE TABLE order\_tbl (
id int(11) NOT NULL AUTO_INCREMENT,
user\_id varchar(255) DEFAULT NULL,
commodity\_code varchar(255) DEFAULT NULL,
count int(11) DEFAULT 0,
money int(11) DEFAULT 0,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

USE account;
DROP TABLE IF EXISTS account\_tbl;
CREATE TABLE account\_tbl (
id int(11) NOT NULL AUTO_INCREMENT,
user\_id varchar(255) DEFAULT NULL,
money int(11) DEFAULT 0,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


#### 3.2.2、common-service中添加依赖



io.seata seata-spring-boot-starter 1.4.2 com.alibaba.cloud spring-cloud-starter-alibaba-seata 2021.0.4.0

#### 3.2.3、加配置



seata:
enabled: true
enable-auto-data-source-proxy: false
application-id: vforumc-user
tx-service-group: default_tx_group
service:
vgroup-mapping:
default_tx_group: default
disable-global-transaction: false
registry:
type: nacos
nacos:
application: seata-server
server-addr: 127.0.0.1:8848
namespace: 1ff3782d-b62d-402f-8bc4-ebcf40254d0a
group: SEATA_GROUP
username: nacos
password: nacos
config:
nacos:
server-addr: 127.0.0.1:8848

做了那么多年开发,自学了很多门编程语言,我很明白学习资源对于学一门新语言的重要性,这些年也收藏了不少的Python干货,对我来说这些东西确实已经用不到了,但对于准备自学Python的人来说,或许它就是一个宝藏,可以给你省去很多的时间和精力。

别在网上瞎学了,我最近也做了一些资源的更新,只要你是我的粉丝,这期福利你都可拿走。

我先来介绍一下这些东西怎么用,文末抱走。


(1)Python所有方向的学习路线(新版)

这是我花了几天的时间去把Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。

最近我才对这些路线做了一下新的更新,知识体系更全面了。

在这里插入图片描述

(2)Python学习视频

包含了Python入门、爬虫、数据分析和web开发的学习视频,总共100多个,虽然没有那么全面,但是对于入门来说是没问题的,学完这些之后,你可以按照我上面的学习路线去网上找其他的知识资源进行进阶。

在这里插入图片描述

(3)100多个练手项目

我们在看视频学习的时候,不能光动眼动脑不动手,比较科学的学习方法是在理解之后运用它们,这时候练手项目就很适合了,只是里面的项目比较多,水平也是参差不齐,大家可以挑自己能做的项目去练练。

在这里插入图片描述

(4)200多本电子书

这些年我也收藏了很多电子书,大概200多本,有时候带实体书不方便的话,我就会去打开电子书看看,书籍可不一定比视频教程差,尤其是权威的技术书籍。

基本上主流的和经典的都有,这里我就不放图了,版权问题,个人看看是没有问题的。

(5)Python知识点汇总

知识点汇总有点像学习路线,但与学习路线不同的点就在于,知识点汇总更为细致,里面包含了对具体知识点的简单说明,而我们的学习路线则更为抽象和简单,只是为了方便大家只是某个领域你应该学习哪些技术栈。

在这里插入图片描述

(6)其他资料

还有其他的一些东西,比如说我自己出的Python入门图文类教程,没有电脑的时候用手机也可以学习知识,学会了理论之后再去敲代码实践验证,还有Python中文版的库资料、MySQL和HTML标签大全等等,这些都是可以送给粉丝们的东西。

在这里插入图片描述

这些都不是什么非常值钱的东西,但对于没有资源或者资源不是很好的学习者来说确实很不错,你要是用得到的话都可以直接抱走,关注过我的人都知道,这些都是可以拿到的。

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 30
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值