分布式事务解决方案:Spring Cloud + Nacos + Seata整合

x33g5p2x  于2022-02-28 转载在 Spring  
字(10.4k)|赞(0)|评价(0)|浏览(533)

一、简介

Seata 是一款开源的分布式事务解决方案,致力于在微服务架构下提供高性能和简单易用的分布式事务服务。
   2019 年 1 月,阿里巴巴中间件团队发起了开源项目 Fescar(Fast & EaSy Commit And Rollback),和社区一起共建开源分布式事务解决方案。Fescar 的愿景是让分布式事务的使用像本地事务的使用一样,简单和高效,并逐步解决开发者们遇到的分布式事务方面的所有难题。
  Fescar 开源后,蚂蚁金服加入 Fescar 社区参与共建,并在 Fescar 0.4.0 版本中贡献了 TCC 模式。
  为了打造更中立、更开放、生态更加丰富的分布式事务开源社区,经过社区核心成员的投票,大家决定对 Fescar 进行品牌升级,并更名为 Seata,意为:Simple Extensible Autonomous Transaction Architecture,是一套一站式分布式事务解决方案。

二、seata-server部署

1、官网下载

我们可以看到Seata的github star数有2万多,说明还是热门的!
我们下载最新版本v1.4.2 https://github.com/seata/seata/releases/download/v1.4.2/seata-server-1.4.2.zip

2、解压到本地

3、修改配置文件

第一步,修改conf/registry.conf,重点修改nacos配置。

  1. registry {
  2. # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  3. type = "nacos"
  4. nacos {
  5. application = "seata-server"
  6. serverAddr = "127.0.0.1:8848"
  7. group = "SEATA_GROUP"
  8. namespace = ""
  9. cluster = "default"
  10. username = "nacos"
  11. password = "nacos"
  12. }
  13. ......
  14. config {
  15. # file、nacos 、apollo、zk、consul、etcd3
  16. type = "nacos"
  17. nacos {
  18. serverAddr = "127.0.0.1:8848"
  19. namespace = ""
  20. group = "SEATA_GROUP"
  21. username = "nacos"
  22. password = "nacos"
  23. dataId = "seataServer.properties"
  24. }
  25. }

最新!现在支持配置dataId,就可以把所有配置放里面。(其他地方的博客还在说,去下载config.txt、nacos-config.sh,然后执行跑到nacos上去,过时了!多关注nacos版本更新)

第二步,在Nacos上新增seataServer.properties

里面的内容:

  1. #For details about configuration items, see https://seata.io/zh-cn/docs/user/configurations.html
  2. #Transport configuration, for client and server
  3. transport.type=TCP
  4. transport.server=NIO
  5. transport.heartbeat=true
  6. transport.enableTmClientBatchSendRequest=false
  7. transport.enableRmClientBatchSendRequest=true
  8. transport.enableTcServerBatchSendResponse=false
  9. transport.rpcRmRequestTimeout=30000
  10. transport.rpcTmRequestTimeout=30000
  11. transport.rpcTcRequestTimeout=30000
  12. transport.threadFactory.bossThreadPrefix=NettyBoss
  13. transport.threadFactory.workerThreadPrefix=NettyServerNIOWorker
  14. transport.threadFactory.serverExecutorThreadPrefix=NettyServerBizHandler
  15. transport.threadFactory.shareBossWorker=false
  16. transport.threadFactory.clientSelectorThreadPrefix=NettyClientSelector
  17. transport.threadFactory.clientSelectorThreadSize=1
  18. transport.threadFactory.clientWorkerThreadPrefix=NettyClientWorkerThread
  19. transport.threadFactory.bossThreadSize=1
  20. transport.threadFactory.workerThreadSize=default
  21. transport.shutdown.wait=3
  22. transport.serialization=seata
  23. transport.compressor=none
  24. #Transaction routing rules configuration, only for the client
  25. service.vgroupMapping.default_tx_group=default
  26. #If you use a registry, you can ignore it
  27. service.default.grouplist=127.0.0.1:8091
  28. service.enableDegrade=false
  29. service.disableGlobalTransaction=false
  30. #Transaction rule configuration, only for the client
  31. client.rm.asyncCommitBufferLimit=10000
  32. client.rm.lock.retryInterval=10
  33. client.rm.lock.retryTimes=30
  34. client.rm.lock.retryPolicyBranchRollbackOnConflict=true
  35. client.rm.reportRetryCount=5
  36. client.rm.tableMetaCheckEnable=false
  37. client.rm.tableMetaCheckerInterval=60000
  38. client.rm.sqlParserType=druid
  39. client.rm.reportSuccessEnable=false
  40. client.rm.sagaBranchRegisterEnable=false
  41. client.rm.sagaJsonParser=fastjson
  42. client.rm.tccActionInterceptorOrder=-2147482648
  43. client.rm.sqlParserType=druid
  44. client.tm.commitRetryCount=5
  45. client.tm.rollbackRetryCount=5
  46. client.tm.defaultGlobalTransactionTimeout=60000
  47. client.tm.degradeCheck=false
  48. client.tm.degradeCheckAllowTimes=10
  49. client.tm.degradeCheckPeriod=2000
  50. client.tm.interceptorOrder=-2147482648
  51. client.undo.dataValidation=true
  52. client.undo.logSerialization=jackson
  53. client.undo.onlyCareUpdateColumns=true
  54. server.undo.logSaveDays=7
  55. server.undo.logDeletePeriod=86400000
  56. client.undo.logTable=undo_log
  57. client.undo.compress.enable=true
  58. client.undo.compress.type=zip
  59. client.undo.compress.threshold=64k
  60. #For TCC transaction mode
  61. tcc.fence.logTableName=tcc_fence_log
  62. tcc.fence.cleanPeriod=1h
  63. #Log rule configuration, for client and server
  64. log.exceptionRate=100
  65. #Transaction storage configuration, only for the server. The file, DB, and redis configuration values are optional.
  66. store.mode=db
  67. store.lock.mode=file
  68. store.session.mode=file
  69. #Used for password encryption
  70. store.publicKey=
  71. #If `store.mode,store.lock.mode,store.session.mode` are not equal to `file`, you can remove the configuration block.
  72. store.file.dir=file_store/data
  73. store.file.maxBranchSessionSize=16384
  74. store.file.maxGlobalSessionSize=512
  75. store.file.fileWriteBufferCacheSize=16384
  76. store.file.flushDiskMode=async
  77. store.file.sessionReloadReadSize=100
  78. #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.
  79. store.db.datasource=druid
  80. store.db.dbType=mysql
  81. store.db.driverClassName=com.mysql.cj.jdbc.Driver
  82. store.db.url=jdbc:mysql://localhost:3306/seata?useUnicode=true&rewriteBatchedStatements=true
  83. store.db.user=root
  84. store.db.password=root
  85. store.db.minConn=5
  86. store.db.maxConn=30
  87. store.db.globalTable=global_table
  88. store.db.branchTable=branch_table
  89. store.db.distributedLockTable=distributed_lock
  90. store.db.queryLimit=100
  91. store.db.lockTable=lock_table
  92. store.db.maxWait=5000
  93. #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.
  94. store.redis.mode=single
  95. store.redis.single.host=127.0.0.1
  96. store.redis.single.port=6379
  97. store.redis.sentinel.masterName=
  98. store.redis.sentinel.sentinelHosts=
  99. store.redis.maxConn=10
  100. store.redis.minConn=1
  101. store.redis.maxTotal=100
  102. store.redis.database=0
  103. store.redis.password=
  104. store.redis.queryLimit=100
  105. #Transaction rule configuration, only for the server
  106. server.recovery.committingRetryPeriod=1000
  107. server.recovery.asynCommittingRetryPeriod=1000
  108. server.recovery.rollbackingRetryPeriod=1000
  109. server.recovery.timeoutRetryPeriod=1000
  110. server.maxCommitRetryTimeout=-1
  111. server.maxRollbackRetryTimeout=-1
  112. server.rollbackRetryTimeoutUnlockEnable=false
  113. server.distributedLockExpireTime=10000
  114. server.session.branchAsyncQueueSize=5000
  115. server.session.enableBranchAsyncRemove=true
  116. #Metrics configuration, only for the server
  117. metrics.enabled=false
  118. metrics.registryType=compact
  119. metrics.exporterList=prometheus
  120. metrics.exporterPrometheusPort=9898

第三步,修改file.conf,修改为db模式,并连接MySQL

  1. ## transaction log store, only used in seata-server
  2. store {
  3. ## store mode: file、db、redis
  4. mode = "db"
  5. ......
  6. ## database store property
  7. db {
  8. ## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp)/HikariDataSource(hikari) etc.
  9. datasource = "druid"
  10. ## mysql/oracle/postgresql/h2/oceanbase etc.
  11. dbType = "mysql"
  12. driverClassName = "com.mysql.cj.jdbc.Driver"
  13. ## if using mysql to store the data, recommend add rewriteBatchedStatements=true in jdbc connection param
  14. url = "jdbc:mysql://localhost:3306/seata?rewriteBatchedStatements=true"
  15. user = "root"
  16. password = "root"
  17. minConn = 5
  18. maxConn = 100
  19. globalTable = "global_table"
  20. branchTable = "branch_table"
  21. lockTable = "lock_table"
  22. queryLimit = 100
  23. maxWait = 5000
  24. }
  25. ......
  26. }

4、seata数据库初始化

  1. -- -------------------------------- The script used when storeMode is 'db' --------------------------------
  2. -- the table to store GlobalSession data
  3. CREATE TABLE IF NOT EXISTS `global_table`
  4. (
  5. `xid` VARCHAR(128) NOT NULL,
  6. `transaction_id` BIGINT,
  7. `status` TINYINT NOT NULL,
  8. `application_id` VARCHAR(32),
  9. `transaction_service_group` VARCHAR(32),
  10. `transaction_name` VARCHAR(128),
  11. `timeout` INT,
  12. `begin_time` BIGINT,
  13. `application_data` VARCHAR(2000),
  14. `gmt_create` DATETIME,
  15. `gmt_modified` DATETIME,
  16. PRIMARY KEY (`xid`),
  17. KEY `idx_status_gmt_modified` (`status` , `gmt_modified`),
  18. KEY `idx_transaction_id` (`transaction_id`)
  19. ) ENGINE = InnoDB
  20. DEFAULT CHARSET = utf8;
  21. -- the table to store BranchSession data
  22. CREATE TABLE IF NOT EXISTS `branch_table`
  23. (
  24. `branch_id` BIGINT NOT NULL,
  25. `xid` VARCHAR(128) NOT NULL,
  26. `transaction_id` BIGINT,
  27. `resource_group_id` VARCHAR(32),
  28. `resource_id` VARCHAR(256),
  29. `branch_type` VARCHAR(8),
  30. `status` TINYINT,
  31. `client_id` VARCHAR(64),
  32. `application_data` VARCHAR(2000),
  33. `gmt_create` DATETIME(6),
  34. `gmt_modified` DATETIME(6),
  35. PRIMARY KEY (`branch_id`),
  36. KEY `idx_xid` (`xid`)
  37. ) ENGINE = InnoDB
  38. DEFAULT CHARSET = utf8;
  39. -- the table to store lock data
  40. CREATE TABLE IF NOT EXISTS `lock_table`
  41. (
  42. `row_key` VARCHAR(128) NOT NULL,
  43. `xid` VARCHAR(128),
  44. `transaction_id` BIGINT,
  45. `branch_id` BIGINT NOT NULL,
  46. `resource_id` VARCHAR(256),
  47. `table_name` VARCHAR(32),
  48. `pk` VARCHAR(36),
  49. `status` TINYINT NOT NULL DEFAULT '0' COMMENT '0:locked ,1:rollbacking',
  50. `gmt_create` DATETIME,
  51. `gmt_modified` DATETIME,
  52. PRIMARY KEY (`row_key`),
  53. KEY `idx_status` (`status`),
  54. KEY `idx_branch_id` (`branch_id`)
  55. ) ENGINE = InnoDB
  56. DEFAULT CHARSET = utf8;
  57. CREATE TABLE IF NOT EXISTS `distributed_lock`
  58. (
  59. `lock_key` CHAR(20) NOT NULL,
  60. `lock_value` VARCHAR(20) NOT NULL,
  61. `expire` BIGINT,
  62. primary key (`lock_key`)
  63. ) ENGINE = InnoDB
  64. DEFAULT CHARSET = utf8mb4;
  65. INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('HandleAllSession', ' ', 0);

5、业务数据库

在每个需要开启seata事务操作的业务数据库下都需要建立此表。
undo_log:回滚日志表。

  1. --日志文件表--
  2. CREATE TABLE IF NOT EXISTS `undo_log`
  3. (
  4. `branch_id` BIGINT NOT NULL COMMENT 'branch transaction id',
  5. `xid` VARCHAR(128) NOT NULL COMMENT 'global transaction id',
  6. `context` VARCHAR(128) NOT NULL COMMENT 'undo_log context,such as serialization',
  7. `rollback_info` LONGBLOB NOT NULL COMMENT 'rollback info',
  8. `log_status` INT(11) NOT NULL COMMENT '0:normal status,1:defense status',
  9. `log_created` DATETIME(6) NOT NULL COMMENT 'create datetime',
  10. `log_modified` DATETIME(6) NOT NULL COMMENT 'modify datetime',
  11. UNIQUE KEY `ux_undo_log` (`xid`, `branch_id`)
  12. ) ENGINE = INNODB
  13. AUTO_INCREMENT = 1
  14. DEFAULT CHARSET = utf8 COMMENT ='AT transaction mode undo table';

6、启动seata-server

双击启动bin目录下的seata-server.bat。(linux系统的启动seata-server.sh)

启动成功后,端口是8091。我们也可以在nacos上看到服务注册上来了。

三、微服务项目集成Seata

1、引入依赖

  1. <dependency>
  2. <groupId>com.alibaba.cloud</groupId>
  3. <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
  4. <version>2021.1</version>
  5. <exclusions>
  6. <!-- 排除依赖 指定版本和服务器端一致 -->
  7. <exclusion>
  8. <groupId>io.seata</groupId>
  9. <artifactId>seata-all</artifactId>
  10. </exclusion>
  11. <exclusion>
  12. <groupId>io.seata</groupId>
  13. <artifactId>seata-spring-boot-starter</artifactId>
  14. </exclusion>
  15. </exclusions>
  16. </dependency>
  17. <dependency>
  18. <groupId>io.seata</groupId>
  19. <artifactId>seata-all</artifactId>
  20. <version>1.4.2</version>
  21. </dependency>
  22. <dependency>
  23. <groupId>io.seata</groupId>
  24. <artifactId>seata-spring-boot-starter</artifactId>
  25. <version>1.4.2</version>
  26. </dependency>

版本号根据自己的项目需要。

2、配置文件

  1. # 分布式事务配置
  2. seata:
  3. enabled: true
  4. enable-auto-data-source-proxy: true #是否开启数据源自动代理,默认为true
  5. tx-service-group: default_tx_group #要与配置文件中的vgroupMapping一致
  6. registry:
  7. type: nacos
  8. nacos:
  9. application: seata-server
  10. server-addr: 127.0.0.1:8848
  11. group: SEATA_GROUP
  12. config:
  13. type: nacos
  14. nacos:
  15. server-addr: 127.0.0.1:8848
  16. group: SEATA_GROUP
  17. dataId: seataServer.properties

到这里配置就结束了,赶紧在项目里面用起来吧!如有遇到搭建问题,可以阅读Seata官方文档或者我们一起探讨。

相关文章