• Seata分布式事务


    CAP原则

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

    image-20210913165914949

    分区性:

    image-20210913170337282

    数据一致性

    image-20210913170606835

    image-20210913171149521

    image-20210913170934911

    image-20210913170955855

    分布式事务协议——2PC

    image-20210913171457040

    假设没有错误情况下:

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

    image-20210913172349232

    image-20210913172449645

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

    image-20210913173240670

    分布式事务协议——3PC

    image-20210913173455292

    Seata

    seata术语

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

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

    image-20210913223237864

    AT模式具体实现步骤

    image-20210913224431014

    实现步骤:

    • 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:softseataseataconf ile.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
      }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52

    此处修改默认配置为: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;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55

    2.seata 注册配置

    编辑E:softseataseataconf egistory.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"
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88

    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
    
    • 1

    -h: nacos地址

    -p: nacos端口

    -t: 命名空间id

    -g: 组名

    -u -w: nacos账户名密码

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

    4.启动seata

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

    创建一个RM

    引入依赖

    
        com.alibaba.cloud
        spring-cloud-starter-alibaba-seata
    
    
    • 1
    • 2
    • 3
    • 4

    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"
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

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

    创建一个TC

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

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

    通过@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?"删除成功":"删除失败";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

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

    先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在。深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小。自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前。因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦

  • 相关阅读:
    小程序怎么做?个人小程序怎么做?新手教程
    数字孪生:实现保险行业数字化转型
    springboot +shiro 缓存用户退出bug
    基于QT的图书管理系统
    树状图怎么画?推荐这个好用的在线树状图软件!
    德人合科技 | 天锐绿盾终端安全管理系统
    Mysql数据库视图,备份,范式
    Prometheus(普罗米修斯)+grafana(3)
    【报名指南】2024年第九届数维杯数学建模挑战赛报名全流程图解
    使用 Python 的基于边缘和基于区域的分割
  • 原文地址:https://blog.csdn.net/m0_59092234/article/details/126114042