# seata1.5-demo **Repository Path**: guyusi-gitee/seata1.5-demo ## Basic Information - **Project Name**: seata1.5-demo - **Description**: seata1.5分布式事务使用案例 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 1 - **Created**: 2023-03-06 - **Last Updated**: 2023-07-13 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 1.软件准备: ## 1.1 seata1.5.2 ### 官网下载:地址:http://seata.io/zh-cn/ server源码:[https://github.com/seata/seata](https://github.com/seata/seata) ### 百度云下载(建议): - 百度下载 链接:[https://pan.baidu.com/s/1eilbSI0YdmupHYI7FroTsw](https://pan.baidu.com/s/1eilbSI0YdmupHYI7FroTsw) 提取码:biam ## 1.2 nacos(采用db模式) 这里不做讲解 # 2.软件配置: ## 2.1 准备工作nacos得配置好 ### 2.1.1 先把nacos起起来 ![在这里插入图片描述](https://img-blog.csdnimg.cn/394d421e4b9944d08f738dec129f27fd.png) ### 2.1.2配置seata:先看长啥样 ![在这里插入图片描述](https://img-blog.csdnimg.cn/f7d272521da244d580cbbce23f2499f1.png) ### 2.1.2配置seata的 application.yml(主要是配置中心和注册中心) ![在这里插入图片描述](https://img-blog.csdnimg.cn/541c686ef7514ed289202596e1adb3d0.png) ### 2.1.3 配置好如图: ```yaml server: port: 7091 spring: application: name: seata-server logging: config: classpath:logback-spring.xml file: path: ${user.home}/logs/seata extend: logstash-appender: destination: 127.0.0.1:4560 kafka-appender: bootstrap-servers: 127.0.0.1:9092 topic: logback_to_logstash console: user: username: seata password: seata seata: config: # support: nacos, consul, apollo, zk, etcd3 type: nacos nacos: server-addr: 127.0.0.1:8848 namespace: group: "SEATA_GROUP" dataId: "seataServer.properties" username: "nacos" password: "nacos" registry: # support: nacos, eureka, redis, zk, consul, etcd3, sofa type: nacos nacos: application: seata-server server-addr: 127.0.0.1:8848 group: "SEATA_GROUP" namespace: username: "nacos" password: "nacos" # store: # support: file 、 db 、 redis # mode: file # server: # service-port: 8091 #If not configured, the default is '${server.port} + 1000' security: secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017 tokenValidityInMilliseconds: 1800000 ignore: urls: /,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/api/v1/auth/login ``` ### 2.1.4 在nacos中配置 seataServer.properties的相关配置内容,该配置存在位置如下图: ![在这里插入图片描述](https://img-blog.csdnimg.cn/e434bb48c5b842dba99229c9416bc17c.png) ### 2.1.5配置好如下图,具体seataServer.properties: ![在这里插入图片描述](https://img-blog.csdnimg.cn/a1a39ae54c1a4356857ede6f4681bfe0.png) ### 2.1.5具体的重要的两处seataServer.properties内容(用中文注释说明了) ```powershell #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 # default_tx_group 这个要注意 后面要和java代码写的一致 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=file store.lock.mode=file store.session.mode=file #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-demo?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 ``` ### 2.1.6需要的sql(绿色为业务库): ![在这里插入图片描述](https://img-blog.csdnimg.cn/a6317f396be24eca86f354caee9fc9c0.png) ### 2.1.6.1自身框架库需要的sql(4张表 ,1.5以前不知道三张表就行): ```sql CREATE TABLE `branch_table` ( `branch_id` bigint(20) NOT NULL, `xid` varchar(128) NOT NULL, `transaction_id` bigint(20) DEFAULT NULL, `resource_group_id` varchar(32) DEFAULT NULL, `resource_id` varchar(256) DEFAULT NULL, `branch_type` varchar(8) DEFAULT NULL, `status` tinyint(4) DEFAULT NULL, `client_id` varchar(64) DEFAULT NULL, `application_data` varchar(2000) DEFAULT NULL, `gmt_create` datetime(6) DEFAULT NULL, `gmt_modified` datetime(6) DEFAULT NULL, PRIMARY KEY (`branch_id`) USING BTREE, KEY `idx_xid` (`xid`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; CREATE TABLE `distributed_lock` ( `lock_key` char(20) NOT NULL, `lock_value` varchar(20) NOT NULL, `expire` bigint(20) DEFAULT NULL, PRIMARY KEY (`lock_key`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; CREATE TABLE `global_table` ( `xid` varchar(128) NOT NULL, `transaction_id` bigint(20) DEFAULT NULL, `status` tinyint(4) NOT NULL, `application_id` varchar(32) DEFAULT NULL, `transaction_service_group` varchar(32) DEFAULT NULL, `transaction_name` varchar(128) DEFAULT NULL, `timeout` int(11) DEFAULT NULL, `begin_time` bigint(20) DEFAULT NULL, `application_data` varchar(2000) DEFAULT NULL, `gmt_create` datetime DEFAULT NULL, `gmt_modified` datetime DEFAULT NULL, PRIMARY KEY (`xid`) USING BTREE, KEY `idx_gmt_modified_status` (`gmt_modified`,`status`) USING BTREE, KEY `idx_transaction_id` (`transaction_id`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; CREATE TABLE `lock_table` ( `row_key` varchar(128) NOT NULL, `xid` varchar(96) DEFAULT NULL, `transaction_id` bigint(20) DEFAULT NULL, `branch_id` bigint(20) NOT NULL, `resource_id` varchar(256) DEFAULT NULL, `table_name` varchar(32) DEFAULT NULL, `pk` varchar(36) DEFAULT NULL, `gmt_create` datetime DEFAULT NULL, `gmt_modified` datetime DEFAULT NULL, PRIMARY KEY (`row_key`) USING BTREE, KEY `idx_branch_id` (`branch_id`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; ``` ### 2.1.6.2业务库需要的sql(每个业务库都要有): ```sql 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`) USING BTREE, UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; ``` ### 2.1.6.3自己写的 java代码业务库需要的sql: seata-count库 ```sql CREATE TABLE `tb_account` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` varchar(255) DEFAULT NULL, `money` int(11) unsigned DEFAULT '0', PRIMARY KEY (`id`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT; CREATE TABLE `tb_account_freeze` ( `xid` varchar(50) NOT NULL, `user_id` int(20) DEFAULT NULL, `freeze_money` int(20) DEFAULT NULL, `state` varchar(20) DEFAULT NULL, PRIMARY KEY (`xid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ``` seata-order库 ```sql CREATE TABLE `tb_order` ( `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', `create_time` datetime DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT; ``` seata-storage库 ```sql CREATE TABLE `tb_storage` ( `id` int(11) NOT NULL AUTO_INCREMENT, `commodity_code` varchar(255) DEFAULT NULL, `count` int(11) unsigned DEFAULT '0', PRIMARY KEY (`id`) USING BTREE, UNIQUE KEY `commodity_code` (`commodity_code`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT; ``` # 3 java重要配置 ## 3.2 pom文件 ```yaml org.springframework.boot spring-boot-starter-web com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery mysql mysql-connector-java com.baomidou mybatis-plus-boot-starter org.springframework.cloud spring-cloud-starter-openfeign com.alibaba.cloud spring-cloud-starter-alibaba-seata seata-spring-boot-starter io.seata io.seata seata-spring-boot-starter 1.5.2 ``` ## 3.2 yaml文件 ```yaml server: port: 8001 spring: application: name: account-service datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/seata-acount?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false username: root password: root cloud: nacos: discovery: server-addr: 127.0.0.1:8848 username: nacos password: nacos mybatis-plus: configuration: # sql输出到控制台,方便开发调试 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 下划线转驼峰 map-underscore-to-camel-case: true seata: enabled: true application-id: ${spring.application.name} tx-service-group: default_tx_group ######### 最容易出错的 事务组名称 要和配置的一致 前面配置文件有说 config: type: nacos nacos: namespace: serverAddr: 127.0.0.1:8848 group: SEATA_GROUP username: "nacos" password: "nacos" data-id: seataServer.properties registry: type: nacos # 使用nacos作为注册中心 nacos: server-addr: localhost:8848 # nacos服务地址 group: SEATA_GROUP # 默认服务分组 namespace: # 默认命名空间 cluster: default # 默认TC集群名称 username: "nacos" password: "nacos" service: vgroup-mapping: default_tx_group: ${spring.application.name}-group # 事务组对应的TC集群名 data-source-proxy-mode: AT ```