分布式微服务架构越来越成熟,使得业务耦合度降低,提高系统的高可用性,分布式事务的重要性也显得尤为的重要,由于使用了Dubbo作为分布式服务架构,所以选用同样阿里系的Seata作为分布式事务,实践证明Seata还是很轻量化的,网上对于这块集成缺乏系统的资料,所以本文将系统的进行说明。
如果注册中心为Zookeeper:Springboot+Zookeeper+Seata+Dubbo组成的微服务架构下,分布式事务解决方案
Nacos官网:https://nacos.io/zh-cn/docs/what-is-nacos.html
Nacos 致力于帮助您发现、配置和管理微服务。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据及流量管理。
Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。 Nacos 是构建以“服务”为中心的现代应用架构 (例如微服务范式、云原生范式) 的服务基础设施。
先下载Nacos服务:https://github.com/alibaba/nacos/releases
1、选择最新版本1.2.1,然后点击下载,并且解压。
2、进入conf目录,找到nacos-mysql.sql,然后在数据库中运行。
CREATE TABLE `permissions` (
`role` varchar(50) NOT NULL,
`resource` varchar(512) NOT NULL,
`action` varchar(8) NOT NULL,
UNIQUE INDEX `uk_role_permission` (`role`,`resource`,`action`) USING BTREE
);
如果在执行上面语句失败,把resource长度设置为250即可。
3、编辑application.properties文件,修改数据库用户名和密码。
server.contextPath=/nacos
server.servlet.contextPath=/nacos
server.port=8848
spring.datasource.platform=mysql
db.num=1
db.url.0=jdbc:mysql://127.0.0.1:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
db.user=root
db.password=yuyi
4、进入bin目录,双击startup.cmd即可启动Nacos系统。
5、浏览器上输入:http://localhost:8848/nacos/index.html,通过初始账号密码:nacos/nacos,即可进入系统。
Seata官网:https://seata.io/zh-cn/docs/overview/what-is-seata.html
Seata 是一款开源的分布式事务解决方案,致力于提供高性能和简单易用的分布式事务服务。Seata 将为用户提供了 AT、TCC、SAGA 和 XA 事务模式,为用户打造一站式的分布式解决方案。
先下载Seata服务:https://seata.io/zh-cn/blog/download.html
1、最新版本1.2.0,然后点击下载,并且解压。这里source和binary都要下载解压。
2、通过source下载得到seata-1.2.0.zip,解压。
3、进入目录\seata-1.2.0\script\server\db,根据不同的数据库进行sql语句执行。
4、进入目录\seata-1.2.0\script\config-center,修改config.txt文件。
这里需要修改存储模式为数据库模式store.mode=db,和修改数据库用户名密码store.db.user=xxx,store.db.password=xxx
transport.type=TCP
transport.server=NIO
transport.heartbeat=true
transport.enableClientBatchSendRequest=false
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
service.vgroupMapping.my_test_tx_group=default
service.default.grouplist=127.0.0.1:8091
service.enableDegrade=false
service.disableGlobalTransaction=false
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=false
client.rm.sqlParserType=druid
client.rm.reportSuccessEnable=false
client.rm.sagaBranchRegisterEnable=false
client.tm.commitRetryCount=5
client.tm.rollbackRetryCount=5
store.mode=db
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
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
store.db.user=root
store.db.password=yuyi
store.db.minConn=5
store.db.maxConn=30
store.db.globalTable=global_table
store.db.branchTable=branch_table
store.db.queryLimit=100
store.db.lockTable=lock_table
store.db.maxWait=5000
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
client.undo.dataValidation=true
client.undo.logSerialization=jackson
server.undo.logSaveDays=7
server.undo.logDeletePeriod=86400000
client.undo.logTable=undo_log
client.log.exceptionRate=100
transport.serialization=seata
transport.compressor=none
metrics.enabled=false
metrics.registryType=compact
metrics.exporterList=prometheus
metrics.exporterPrometheusPort=9898
5、进入目录\seata-1.2.0\script\config-center\nacos,发现windows下只能通过python把seata配置文件注册到Nacos。
6、下载Python服务:https://www.python.org/downloads/,选择相应版本下载,下载完成后,双击执行python-3.8.2.exe
Windows x86-64 executable installer | Windows | for AMD64/EM64T/x64 | b5df1cbb2bc152cd70c3da9151cb510b | 27586384 |
安装完成后,打开Cmd,执行python,如果出来版本号,安装成功。
7、再次进入目录\seata-1.2.0\script\config-center\nacos,然后打开Cmd,输入python nacos-config.py localhost:8848
如果出现init nacos config finished, please start seata-server.说明初始化Seata配置到Nacos成功。
8、通过binary下载得到seata-server-1.2.0.zip,解压。
9、进入conf目录,修改file.conf文件和registry.conf文件。
修改file.conf文件,修改mode为db,修改db的数据库账号密码。
## transaction log store, only used in seata-server
store {
## store mode: file、db
mode = "db"
## 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) etc.
datasource = "druid"
## mysql/oracle/postgresql/h2/oceanbase etc.
dbType = "mysql"
driverClassName = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://127.0.0.1:3306/seata"
user = "root"
password = "yuyi"
minConn = 5
maxConn = 30
globalTable = "global_table"
branchTable = "branch_table"
lockTable = "lock_table"
queryLimit = 100
maxWait = 5000
}
}
修改registry.conf文件,type改为nacos
registry {
# file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
type = "nacos"
nacos {
application = "seata-server"
serverAddr = "localhost"
namespace = ""
cluster = "default"
username = ""
password = ""
}
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"
}
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 = "nacos"
nacos {
serverAddr = "localhost:8848"
namespace = ""
group = "SEATA_GROUP"
username = ""
password = ""
}
consul {
serverAddr = "127.0.0.1:8500"
}
apollo {
appId = "seata-server"
apolloMeta = "http://192.168.1.204:8801"
namespace = "application"
}
zk {
serverAddr = "127.0.0.1:2181"
sessionTimeout = 6000
connectTimeout = 2000
username = ""
password = ""
}
etcd3 {
serverAddr = "http://localhost:2379"
}
file {
name = "file.conf"
}
}
10、进入bin目录,双击seata-server.bat即可启动Seata服务。
1. Maven引入相应的Jar
org.apache.dubbo
dubbo-spring-boot-starter
org.apache.dubbo
dubbo-config-spring
io.seata
seata-spring-boot-starter
org.apache.dubbo
dubbo-registry-nacos
com.alibaba.nacos
nacos-client
3. 打开application.yml文件配置,配置Nacos作为为Dubbo注册中心。
dubbo:
application:
name: ${spring.application.name}
protocol:
name: dubbo
port: 20801
registry:
address: nacos://127.0.0.1:8848
config-center:
address: ${dubbo.registry.address}
metadata-report:
address: ${dubbo.registry.address}
scan:
basePackages: yui
3. 进入目录\seata-1.2.0\script\client\spring,复制application.yml中内容到项目中的application.yml中。
seata:
enabled: true
application-id: applicationName
tx-service-group: my_test_tx_group
enable-auto-data-source-proxy: true
use-jdk-proxy: false
excludes-for-auto-proxying: firstClassNameForExclude,secondClassNameForExclude
client:
rm:
async-commit-buffer-limit: 1000
report-retry-count: 5
table-meta-check-enable: false
report-success-enable: false
saga-branch-register-enable: false
lock:
retry-interval: 10
retry-times: 30
retry-policy-branch-rollback-on-conflict: true
tm:
commit-retry-count: 5
rollback-retry-count: 5
undo:
data-validation: true
log-serialization: jackson
log-table: undo_log
log:
exceptionRate: 100
service:
vgroup-mapping:
my_test_tx_group: default
grouplist:
default: 127.0.0.1:8091
enable-degrade: false
disable-global-transaction: false
transport:
shutdown:
wait: 3
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
worker-thread-size: default
boss-thread-size: 1
type: TCP
server: NIO
heartbeat: true
serialization: seata
compressor: none
enable-client-batch-send-request: true
config:
type: nacos
consul:
server-addr: 127.0.0.1:8500
apollo:
apollo-meta: http://192.168.1.204:8801
app-id: seata-server
namespace: application
etcd3:
server-addr: http://localhost:2379
nacos:
namespace:
serverAddr: localhost:8848
group: SEATA_GROUP
userName: ""
password: ""
zk:
server-addr: 127.0.0.1:2181
session-timeout: 6000
connect-timeout: 2000
username: ""
password: ""
registry:
type: nacos
consul:
server-addr: 127.0.0.1:8500
etcd3:
serverAddr: http://localhost:2379
eureka:
weight: 1
service-url: http://localhost:8761/eureka
nacos:
application: seata-server
server-addr: localhost:8848
namespace:
userName: ""
password: ""
redis:
server-addr: localhost:6379
db: 0
password:
timeout: 0
sofa:
server-addr: 127.0.0.1:9603
region: DEFAULT_ZONE
datacenter: DefaultDataCenter
group: SEATA_GROUP
addressWaitTime: 3000
application: default
zk:
server-addr: 127.0.0.1:2181
session-timeout: 6000
connect-timeout: 2000
username: ""
password: ""
本次测试需要至少启动两个服务,这里选用了yui3-system-provider和yui3-test-web服务
测试类TestEMgrImpl ,使用分布式事务,需要再方法上加入注解@GlobalTransactional(rollbackFor = Exception.class)
@Slf4j
@Service
public class TestEMgrImpl extends BaseMgrImpl
implements TestEMgr {
@Reference
private SysAdMgr sysAdMgr;
@GlobalTransactional(rollbackFor = Exception.class)
@Override
public void testSeata() {
SysAdDto adDto = sysAdMgr.getById(4342213847225347L);
adDto.getSysAdVo().setNm("seata test");
sysAdMgr.update(adDto.getSysAdVo());
TestEDto dto = getById(4635127064400896L);
dto.getTestEVo().setA15("seata test");
update(dto.getTestEVo());
BssExpUtils.error("@GlobalTransactional test", log);
}
}
1. 原先t_sys_ad表中数据为
2. 通过Debug调试模式进行测试,执行到BssExpUtils.error("@GlobalTransactional test", log),再次查看t_sys_ad表中数据,发现表中数据已经被更新掉, t_test_e中表中的数据同样也被更新了。
3. 打开seata数据库中的branch_table中可以看到记录了需要回滚的数据。
4. 最后抛出错误,数据库数据回滚到1状态,说明分布式事务在发生错误后,对数据库进行了反向操作。
Nacos和Seata都在迭代更新当中,不同的版本差异明显。
Nacos作为注册中心,比zookeeper功能要强大,但是相关的几张表表名没有统一的前缀,如果更业务数据库表放在一起,会显得很杂乱,不太友好。
Seata作为分布式事务还是比较轻量化,耦合性低的特点,表名可以自行定义比较友好。