seata整合nacos小Demo实现

seata1.7 nacos2.0.2

一、开启nacos

1.docker上运行nacos 主机模式运行

docker run --name nacos-quick -e MODE=standalone --network=host nacos/nacos-server:2.0.2

2.防火墙开启端口8848 9848 9849

[root@localhost ~]# firewall-cmd --zone=public --add-port=9848/tcp --permanent;
success
[root@localhost ~]# firewall-cmd --zone=public --add-port=8848/tcp --permanent;
success
[root@localhost ~]# firewall-cmd --zone=public --add-port=9849/tcp --permanent;
success
[root@localhost ~]# firewall-cmd --reload
success
[root@localhost ~]# firewall-cmd --list-ports
9986/tcp 2181/tcp 9092/tcp 9848/tcp 8848/tcp 9849/tcp
[root@localhost ~]# 

3.登陆nacos

账号密码都是nacos

二.配置

1.配置seata

下载

官网:https://github.com/seata/seata/releases/tag/v1.7.0

修改配置文件

1.5.0之前的版本配置文件是有多个的,都位于`conf`文件夹下,如`file.conf`,`registry,conf`等。在1.5.0版本之后都整合到一个配置文件里了,即`application.yml`。以下配置项请按照自己版本查找修改。

以seata-1.7.0为例,打开`conf/application.yml`进行修改,重点修改nacos部分配置。

其中的:application.example.yml  各种注册中心,配置中心配置方式,默认是配置本地,这里以配置

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: 10.10.61.20:8848
      namespace:
      group: SEATA_GROUP
      username: nacos
      password: nacos
      context-path:
      ##if use MSE Nacos with auth, mutex with username/password attribute
      #access-key:
      #secret-key:
      data-id: seataServer.properties
  registry:
    # support: nacos, eureka, redis, zk, consul, etcd3, sofa
    type: nacos
    nacos:
      application: seata-server
      server-addr: 10.10.61.20:8848
      group: SEATA_GROUP
      namespace:
      cluster: default
      username:
      password:
      context-path:
      ##if use MSE Nacos with auth, mutex with username/password attribute
      #access-key:
      #secret-key:
  store:
    # support: file 、 db 、 redis
    mode: file
#  server:
#    service-port: 8091 #If not configured, the default is '${server.port} + 1000'
  security:
    secretKey: 
    tokenValidityInMilliseconds: 1800000
    ignore:
      urls: /,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.jpeg,/**/*.ico,/api/v1/auth/login

修改成功后,意味着seata将从nacos获取配置信息,同时注册自身服务到nacos中心。

2.nacos配置

上面配置项中有一项:`seata.config.data-id=seataServer.properties`,意思为要读nacos上的`seataServer.properties`配置文件,接下来去`Nacos`创建该配置文件,注意`Group`与第2步中的保持一致,这里是`SEATA_GROUP`。

配置内容从`seata-server-1.7.0/seata/script/config-center/config.txt`粘贴修改而来,这里只使用对我们有用的配置,主要是`数据库配置`信息。

#Transaction storage configuration, only for the server.
store.mode=db
store.lock.mode=db
store.session.mode=db

#These configurations are required if the `store mode` is `db`.
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.cj.jdbc.Driver
store.db.url=jdbc:mysql://10.10.36.189:3306/seata?useSSL=false&useUnicode=true&rewriteBatchedStatements=true
store.db.user=root
store.db.password=123456
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


-- 启动nacos bin目录下 cmd > startup.cmd -m standalone

数据库建表

在seata数据库内,执行seata-server-1.7.0/seata/script/server/db目录下的sql脚本(根据数据库类

-- -------------------------------- The script used when storeMode is 'db' --------------------------------
-- the table to store GlobalSession data
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_status_gmt_modified` (`status` , `gmt_modified`),
    KEY `idx_transaction_id` (`transaction_id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4;

-- 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 = utf8mb4;

-- the table to store lock data
CREATE TABLE IF NOT EXISTS `lock_table`
(
    `row_key`        VARCHAR(128) NOT NULL,
    `xid`            VARCHAR(128),
    `transaction_id` BIGINT,
    `branch_id`      BIGINT       NOT NULL,
    `resource_id`    VARCHAR(256),
    `table_name`     VARCHAR(32),
    `pk`             VARCHAR(36),
    `status`         TINYINT      NOT NULL DEFAULT '0' COMMENT '0:locked ,1:rollbacking',
    `gmt_create`     DATETIME,
    `gmt_modified`   DATETIME,
    PRIMARY KEY (`row_key`),
    KEY `idx_status` (`status`),
    KEY `idx_branch_id` (`branch_id`),
    KEY `idx_xid` (`xid`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4;

CREATE TABLE IF NOT EXISTS `distributed_lock`
(
    `lock_key`       CHAR(20) NOT NULL,
    `lock_value`     VARCHAR(20) NOT NULL,
    `expire`         BIGINT,
    primary key (`lock_key`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4;

INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('AsyncCommitting', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('RetryCommitting', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('RetryRollbacking', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('TxTimeoutCheck', ' ', 0);

型),创建服务端所需的表。此处选择:mysql

启动seata-server

运行`bin`下的`bat`脚本启动服务。

访问:http://127.0.0.1:7091

默认账号与密码都是seataseata AT模式实现

代码

配置seata-AT相关快照/全局锁/快照表数据库

配置数据库

TM数据库-seata

源sql: seata-server-1.7.0/script/server/db 中

各个RM数据库

源sql: https://seata.io/zh-cn/docs/dev/mode/at-mode.html

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;

配置文件

在application.yml文件中配置, 每个微服务都要

# Tomcat
server:
  port: 8092
# Spring
spring:
  application:
    # 应用名称
    name: stock-service
    #  profiles:
    # 环境配置
  #    active: dev
  cloud:
    nacos:
      discovery:
        # 服务注册地址
        server-addr: 10.10.61.20:8848
        namespace:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://10.10.36.189:3306/seata-stock?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
    username: root
    password: 123456
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

#seata客户端配置
seata:
  enabled: true
  application-id: seata_tx
  tx-service-group: seata_tx_group
  service:
    vgroup-mapping:
      seata_tx_group: default
  registry:
    type: nacos
    nacos:
      application: seata-server
      server-addr: 10.10.61.20:8848
      namespace:
      group: SEATA_GROUP
  data-source-proxy-mode: AT

测试

正常:http://localhost:8088/businesses/purchase?rollback=false&count=2

超库存:http://localhost:8088/businesses/purchase?rollback=false&count=12

超余额:http://localhost:8088/businesses/purchase?rollback=false&count=8

优缺点

优点

- 一阶段完成直接提交事务,释放资源,性能较好
- 利用全局锁实现读写隔离
- 没有代码侵入,框架自动完成回滚与提交

缺点

- 两阶段之间存在数据不一致情况,只能保证最终一致
- 框架的快照功能影响性能,但比XA模式要好很多

源码地址+所有资料:

seata1.7+nacos2.0.2+springboot: seata整合nacos小Demoicon-default.png?t=N7T8https://gitee.com/fuyan_u/seata1.7-nacos2.0.2-springboot.git

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

伏颜.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值