连接是尚硅谷老师用seata 0.9版本演示微服务全局事务回滚的视频
https://www.bilibili.com/video/BV18E411x7eT?from=search&seid=8398717443823471663
由于现在seata已经跟新到1.3了,从1.0开始。坑非常多,今天花了一天时间配置了seata1.2,记录一下我配置的过程
Nacos的下载,安装就不再写了
首先来到seata官网https://seata.io/zh-cn/index.html
下载seata1.2
完成后解压
修改里面registry.conf的配置文件,将registry和config方式都改成nacos,写好地址
registry { #file 、nacos 、eureka、redis、zk、consul、etcd3、sofa type = “nacos”
nacos {
application = “seata-server”
serverAddr = “127.0.0.1”
namespace = “public”
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 = “seata-config”
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” } }
注意!
1.2版本不在提供db数据库文件,需前往
https://github.com/seata/seata/tree/develop/script/server
db目录下查看。然后创建seata数据库,利用连接里的sql语句创建三张表,我贴在下面
> CREATE TABLE IF NOT EXISTS `global_table`
(
`xid` VARCHAR(128) NOT NULL,
`transaction_id` BIGINT,
`status` TINYINT NOT NULL,
`application_id` VARCHAR(32),
`transaction_service_group` VARCHAR(32),
`transaction_name` VARCHAR(128),
`timeout` INT,
`begin_time` BIGINT,
`application_data` VARCHAR(2000),
`gmt_create` DATETIME,
`gmt_modified` DATETIME,
PRIMARY KEY (`xid`),
KEY `idx_gmt_modified_status` (`gmt_modified`, `status`),
KEY `idx_transaction_id` (`transaction_id`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8;
>
> -- the table to store BranchSession data CREATE TABLE IF NOT EXISTS `branch_table` (
> `branch_id` BIGINT NOT NULL,
> `xid` VARCHAR(128) NOT NULL,
> `transaction_id` BIGINT,
> `resource_group_id` VARCHAR(32),
> `resource_id` VARCHAR(256),
> `branch_type` VARCHAR(8),
> `status` TINYINT,
> `client_id` VARCHAR(64),
> `application_data` VARCHAR(2000),
> `gmt_create` DATETIME(6),
> `gmt_modified` DATETIME(6),
> PRIMARY KEY (`branch_id`),
> KEY `idx_xid` (`xid`) ) ENGINE = InnoDB DEFAULT CHARSET = utf8;
>
> -- the table to store lock data CREATE TABLE IF NOT EXISTS `lock_table` (
> `row_key` VARCHAR(128) NOT NULL,
> `xid` VARCHAR(96),
> `transaction_id` BIGINT,
> `branch_id` BIGINT NOT NULL,
> `resource_id` VARCHAR(256),
> `table_name` VARCHAR(32),
> `pk` VARCHAR(36),
> `gmt_create` DATETIME,
> `gmt_modified` DATETIME,
> PRIMARY KEY (`row_key`),
> KEY `idx_branch_id` (`branch_id`) ) ENGINE = InnoDB DEFAULT CHARSET = utf8;
每个业务数据库需要建立一张undo_log表记录回滚信息
drop table `undo_log`;
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;
接下来我们需要将配置推送到nacos
由于1.2版本不在包含我们需要的config.txt和nacos-config.sh
需要到https://github.com/seata/seata/tree/1.2.0/script/config-center
提取(注意nacos-config.sh在nacos目录下)
config文件如下,主要要修改的地方被我加粗斜体了,主要是添加service.vgroupMapping,修改数据库连接信息。修改完成后将config放到seata目录下
(0.9版本为vgroup_mapping,1.2版本全部改为驼峰命名方式)
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.seata-storage-service-group=default
service.vgroupMapping.seata-order-service-group=default
service.vgroupMapping.seata-account-service-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=123
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
然后我们将配置推送到nacos
使用Git Bash 打开nacos-config.sh 所在路径
输入(我是在本机,所以地址用locahost)
sh nacos-config.sh localhost
提交
出现这个就说明成功了
进入到nacos里,可以看到一大推配置,我们自己的vgroupMapping也加了进来
点击bin目录下的seata-server.bat就可以启动seata
下面开始编写我们的demo,其中order项目如下
pom文件
注意spring-cloud-alibaba-seata的2.2.0.RELEASE以上版本才支持seata的yml文件配置!一定要2.2.0以上!
<!-- seata-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-seata</artifactId>
<version>2.2.0.RELEASE</version>
<exclusions>
<exclusion>
<groupId>io.seata</groupId>
<artifactId>seata-all</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-all</artifactId>
<version>1.2.0</version>
</dependency>
yml配置文件,主要是seata部分
更多的参数配置请查看官方文档
https://seata.io/zh-cn/docs/user/configurations.html
server:
port: 2001
mybatis:
mapperLocations: classpath:mapper/*.xml
spring:
application:
name: seata-order-service
cloud:
nacos:
discovery:
server-addr: localhost:8848
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/seata_order?useUnicode=true&characterEncoding=UTF8&serverTimezone=UTC
username: root
password: 123
feign:
hystrix:
enabled: false
logging:
level:
io:
seata: info
seata:
enabled: true
application-id: ${spring.application.name}
tx-service-group: ${spring.application.name}-group
enable-auto-data-source-proxy: true
config:
type: nacos
nacos:
namespace:
serverAddr: localhost:8848
group: SEATA_GROUP
userName: "nacos1"
password: "nacos"
registry:
type: nacos
nacos:
application: seata-server
server-addr: localhost:8848
namespace:
userName: "nacos1"
password: "nacos"
然后在我们的业务方法上添加注解就可以实现全局事务处理了
@GlobalTransactional(rollbackFor = Exception.class)
public void create(Order order){
log.info("----->开始新建订单");
//新建订单
orderDao.create(order);
//扣减库存
log.info("----->订单微服务开始调用库存,做扣减Count");
storageService.decrease(order.getProductId(),order.getCount());
log.info("----->订单微服务开始调用库存,做扣减end");
//扣减账户
log.info("----->订单微服务开始调用账户,做扣减Money");
accountService.decrease(order.getUserId(),order.getMoney());
log.info("----->订单微服务开始调用账户,做扣减end");
//修改订单状态,从零到1代表已经完成
log.info("----->修改订单状态开始");
orderDao.update(order.getUserId(),0);
log.info("----->修改订单状态结束");
log.info("----->下订单结束了");
}
具体的业务代码可以看老师的视频
主要坑的是配置部分,我已经可以实现全局业务回滚了。一切以官方文档为准