Seata分布式事务

CAP原则

CAP原则又称CAP定理,指的是在一个分布式系统中,一致性(Consistency)、可用性(Availability)、分区容错性(Partition tolerance)。CAP 原则指的是,这三个要素最多只能同时实现两点,不可能三者兼顾。

Seata分布式事务_第1张图片

分区性:

Seata分布式事务_第2张图片

数据一致性

Seata分布式事务_第3张图片

Seata分布式事务_第4张图片

Seata分布式事务_第5张图片

Seata分布式事务_第6张图片

分布式事务协议——2PC

Seata分布式事务_第7张图片

假设没有错误情况下:

Seata分布式事务_第8张图片

假设其中某一参与者出错:

Seata分布式事务_第9张图片

Seata分布式事务_第10张图片

不管最后结果如何,第二阶段都会结束当前事务

Seata分布式事务_第11张图片

分布式事务协议——3PC

Seata分布式事务_第12张图片

Seata

seata术语

seata有四种模式:AT、TCC、Sage、XA,其中AT模式是最常用的模式

详情参见https://www.pianshen.com/article/34341263271/

Seata分布式事务_第13张图片

AT模式具体实现步骤

Seata分布式事务_第14张图片

实现步骤:

  • TM端使用@GolableTranscation进行全局事务开启、提交、回滚
  • TM开始RPC调用远程服务
  • RM端seata-client通过扩展DataSourceProxy,实现自动生成undo-log与TC上报
  • TM告知TC提交/回滚全局事务
  • TC通知RM各自执行commit/rollback操作,同时清除undo-log

win10启动seata,需要64位java8,如遇闪退情况需检查此问题

1.seata 数据源配置

下载seata程序包,此处版本为1.3.0

修改配置文件E:\soft\seata\seata\conf\file.conf


## transaction log store, only used in seata-server
store {
  ## store mode: file、db、redis
  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)/HikariDataSource(hikari) etc.
    datasource = "druid"
    ## mysql/oracle/postgresql/h2/oceanbase etc.
    dbType = "mysql"
    driverClassName = "com.mysql.cj.jdbc.Driver"
    url = "jdbc:mysql://host:3306/seata?characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai"
    user = "root"
    password = "xxx"
    minConn = 5
    maxConn = 30
    globalTable = "global_table"
    branchTable = "branch_table"
    lockTable = "lock_table"
    queryLimit = 100
    maxWait = 5000
  }

  ## redis store property
  redis {
    host = "47.100.42.118"
    port = "6379"
    password = ""
    database = "0"
    minConn = 1
    maxConn = 10
    queryLimit = 100
  }

}

此处修改默认配置为:seata数据源类型为db,并配置mysql数据源

如果用mysql作为数据源,需要初始化SQL建表,下面贴出:

DROP TABLE IF EXISTS `branch_table`;
CREATE TABLE `branch_table`  (
  `branch_id` bigint(20) NOT NULL,
  `xid` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `transaction_id` bigint(20) NULL DEFAULT NULL,
  `resource_group_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `resource_id` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `branch_type` varchar(8) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `status` tinyint(4) NULL DEFAULT NULL,
  `client_id` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `application_data` varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `gmt_create` datetime(0) NULL DEFAULT NULL,
  `gmt_modified` datetime(0) NULL DEFAULT NULL,
  PRIMARY KEY (`branch_id`) USING BTREE,
  INDEX `idx_xid`(`xid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
 
-- ----------------------------
-- Table structure for global_table
-- ----------------------------
DROP TABLE IF EXISTS `global_table`;
CREATE TABLE `global_table`  (
  `xid` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `transaction_id` bigint(20) NULL DEFAULT NULL,
  `status` tinyint(4) NOT NULL,
  `application_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `transaction_service_group` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `transaction_name` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `timeout` int(11) NULL DEFAULT NULL,
  `begin_time` bigint(20) NULL DEFAULT NULL,
  `application_data` varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `gmt_create` datetime(0) NULL DEFAULT NULL,
  `gmt_modified` datetime(0) NULL DEFAULT NULL,
  PRIMARY KEY (`xid`) USING BTREE,
  INDEX `idx_gmt_modified_status`(`gmt_modified`, `status`) USING BTREE,
  INDEX `idx_transaction_id`(`transaction_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
 
-- ----------------------------
-- Table structure for lock_table
-- ----------------------------
DROP TABLE IF EXISTS `lock_table`;
CREATE TABLE `lock_table`  (
  `row_key` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `xid` varchar(96) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `transaction_id` bigint(20) NULL DEFAULT NULL,
  `branch_id` bigint(20) NOT NULL,
  `resource_id` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `table_name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `pk` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `gmt_create` datetime(0) NULL DEFAULT NULL,
  `gmt_modified` datetime(0) NULL DEFAULT NULL,
  PRIMARY KEY (`row_key`) USING BTREE,
  INDEX `idx_branch_id`(`branch_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

2.seata 注册配置

编辑E:\soft\seata\seata\conf\registory.conf

registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "nacos"

  nacos {
    application = "seata-server"
    serverAddr = "127.0.0.1:8848"
    # group = "test"
    namespace = "fcf48d9c-1b25-413a-b365-2fa20ad3568d"
    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"
    namespace = "fcf48d9c-1b25-413a-b365-2fa20ad3568d"
    group = "SEATA_GROUP"
    username = "nacos"
    password = "nacos"
  }
  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"
  }
}

3.推送详细配置到nacos

进入nacos项目地址,下载配置文件,或复制粘贴到本地

https://github.com/seata/seata/tree/1.3.0/script/config-center

  • 在seata/script/config-center/中找到config.txt文件

  • 在seata/script/config-center/nacos/中找到nacos-config.sh脚本

下载完成后config.txt放在bin同级目录下,bin同级目录下新建script文件夹,将sh脚本放入其中

进入script目录,cmd:启动脚本

sh nacos-config.sh -h localhost -p 8848 -t fcf48d9c-1b25-413a-b365-2fa20ad3568d -g  STATE_GROUP -u nacos -w nacos

-h: nacos地址

-p: nacos端口

-t: 命名空间id

-g: 组名

-u -w: nacos账户名密码

在nacos上对应命名空间查看配置文件是否上传成功

4.启动seata

进入目录 E:\soft\seata\seata\bin 启动seata-server.bat,如遇闪退,可以在cmd命令行中执行bat启动程序,这种方式可以查看错误日志

创建一个RM

引入依赖

<dependency>
    <groupId>com.alibaba.cloudgroupId>
    <artifactId>spring-cloud-starter-alibaba-seataartifactId>
dependency>

seata配置

seata:
  application-id: seata-server
  tx-service-group: my_test_tx_group
  config:
    type: nacos
    nacos:
      namespace: fcf48d9c-1b25-413a-b365-2fa20ad3568d
      server-addr: localhost:8848
      group: STATE_GROUP
      username: "nacos"
      password: "nacos"
  registry:
    type: nacos
    nacos:
      application: seata-server
      server-addr: localhost:8848
      # group:
      namespace: fcf48d9c-1b25-413a-b365-2fa20ad3568d
      username: "nacos"
      password: "nacos"

RM的业务代码与其他普通项目并无区别…

创建一个TC

同样引入pom依赖、做好seata配置,与RM无异

@GlobalTransactional
public String deleteUser(){
    //微服务1
    userService.selectUser();
    //微服务2
    userService.delUser();
    int i = userMapper.deleteById("1");
    return i==1?"删除成功":"删除失败";
}

通过@GlobalTransactional注解进行全局事务管理,微服务一方失败都会导致全局回滚

password: "nacos"

RM的业务代码与其他普通项目并无区别......

## 创建一个TC

同样引入pom依赖、做好seata配置,与RM无异

```java
@GlobalTransactional
public String deleteUser(){
    //微服务1
    userService.selectUser();
    //微服务2
    userService.delUser();
    int i = userMapper.deleteById("1");
    return i==1?"删除成功":"删除失败";
}

通过@GlobalTransactional注解进行全局事务管理,微服务一方失败都会导致全局回滚

你可能感兴趣的:(微服务,分布式,java,微服务,spring,cloud)