• 分布式事务


    SpringCloud 整合 TX-LCN分布式事务框架
    **微服务兴起,分布式事务也成为亟需解决的难题,业界解决方案很多,今天介绍一个我目前觉得最好用 **
    的TX-LCN。

    一、TX-LCN介绍
    image.png

    image.png

    TX-LCN由两大模块组成, TxClient、TxManager,TxClient就是你自己的服务,TxManager作为分布式
    事务的服务端。事务发起方或者参与反都由TxClient端来控制。
    ServerA调用ServerB,同属于一个共同业务逻辑,比如买东西的业务流程:下单(订单服务)-扣除钱包金
    额(钱包服务)-减库存(库存服务),涉及到3个服务的调用,这个买东西的操作,下单-扣钱-减库存三个操
    作必须保证原子性。这里涉及到3个服务怎么保证原子性呢?
    TX-LCN是这样处理的:
    ServerA(事务发起方)发起调用时,创建一个事务组,会生成一个唯一的GroupId,这个GroupId会顺着
    服务调用链传递,每调用一个参与方服务,就会把这个参与方的事务信息通知给TxManager,加入该事
    务组。发起方收到调用返回(有可能是成功执行或者报错),将发起方执行结果状态通知给
    TxManager,TxManager将根据事务最终状态和事务组的信息来通知相应的参与模块提交或回滚事务,
    并返回结果给事务发起方。
    官网:https://github.com/codingapi/tx-lcn

    **TX-LCN的3种模式 **
    LCN5.0.2有3种模式,分别是LCN模式,TCC模式,TXC模式
    **LCN模式: **
    LCN模式是通过代理Connection的方式实现对本地事务的操作,然后在由TxManager统一协调控制事
    务。当本地事务提交回滚或者关闭连接时将会执行假操作,该代理的连接将由LCN连接池管理。
    该模式的特点:

    • 该模式对代码的嵌入性为低。
      - 该模式仅限于本地存在连接对象且可通过连接对象控制事务的模块。
      - 该模式下的事务提交与回滚是由本地事务方控制,对于数据一致性上有较高的保障。
      - 该模式缺陷在于代理的连接需要随事务发起方一共释放连接,增加了连接占用的时间。

    **TCC模式: **
    TCC事务机制相对于传统事务机制(X/Open XA Two-Phase-Commit),其特征在于它不依赖资源管理
    器(RM)对XA的支持,而是通过对(由业务系统提供的)业务逻辑的调度来实现分布式事务。主要由三步
    操作,Try: 尝试执行业务、 Confirm:确认执行业务、 Cancel: 取消执行业务。
    该模式的特点:
    https://blog.csdn.net/bbcckkl/article/details/104524095
    **TXC模式: **
    TXC模式命名来源于淘宝,实现原理是在执行SQL之前,先查询SQL的影响数据,然后保存执行的SQL快
    走信息和创建锁。当需要回滚的时候就采用这些记录数据回滚数据库,目前锁实现依赖 redis 分布式锁
    控制。
    该模式的特点:
    **二、LCN 服务者配置 **
    **1、新建springboot项目 **
    - 该模式对代码的嵌入性为低。
    - 该模式仅限于本地存在连接对象且可通过连接对象控制事务的模块。
    - 该模式下的事务提交与回滚是由本地事务方控制,对于数据一致性上有较高的保障。
    - 该模式缺陷在于代理的连接需要随事务发起方一共释放连接,增加了连接占用的时间。
    - 该模式对代码的嵌入性高,要求每个业务需要写三种步骤的操作。
    - 该模式对有无本地事务控制都可以支持使用面广。
    - 数据一致性控制几乎完全由开发者控制,对业务开发难度要求高。
    - 该模式同样对代码的嵌入性低。
    - 该模式仅限于对支持SQL方式的模块支持。
    - 该模式由于每次执行SQL之前需要先查询影响数据,因此相比LCN模式消耗资源与时间要多。
    - 该模式不会占用 数据库 的连接资源

    **三、LCN 服务者配置 **
    1、新建springboot项目
    image.png

    2、导入依赖包

    <dependency>
                <groupId>com.codingapi.txlcn</groupId>
                <artifactId>txlcn-tm</artifactId>
                <version>5.0.2.RELEASE</version>
            </dependency>
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.47</version>
            </dependency>
    
            <!--数据库连接池依赖-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-starter</artifactId>
                <version>1.1.22</version>
            </dependency>
    
    
            <!--jpa的依赖-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            </dependency>
    
            <!-- redis的依赖-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
                <exclusions>
                    <exclusion>
                        <groupId>redis.clients</groupId>
                        <artifactId>jedis</artifactId>
                    </exclusion>
                    <exclusion>
                        <artifactId>lettuce-core</artifactId>
                        <groupId>io.lettuce</groupId>
                    </exclusion>
                </exclusions>
            </dependency>
    
            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
            </dependency>
            <!-- spring2.X集成redis所需common-pool2,使用jedis必须依赖它-->
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-pool2</artifactId>
            </dependency>
    
    
     
    
    • 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

    2.2 禁止DataSource 注入到spring 容器

    @EnableEurekaServer
    @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class,
            DataSourceTransactionManagerAutoConfiguration.class,
            HibernateJpaAutoConfiguration.class,
            DruidDataSourceAutoConfigure.class})
    public class EurekaApplication {
        public static void main(String[] args) {
            SpringApplication.run(EurekaApplication.class,args);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    **3、搭建txserver端配置文件 **
    3.1 配置服务器端口和服务名

    spring.application.name=TransactionManager
    server.port=7970
    
    • 1
    • 2

    3.2 配置数据源

    spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.datasource.druid.url=jdbc:mysql://211.149.142.20:3306/hsp_dev1?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    spring.datasource.druid.username=root
    spring.datasource.druid.password=123456
    spring.datasource.druid.initial-size=5
    spring.datasource.druid.max-active=500
    spring.datasource.druid.min-idle=10
    spring.datasource.druid.max-wait=50
    #是否缓存preparedStatement,也就是PSCachePSCache对支持游标的数据库性能提升巨大,比如说oracle。
    #在mysql5.5以下的版本中没有PSCache功能,建议关闭掉。
    spring.datasource.druid.pool-prepared-statements=true
    #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    spring.datasource.druid.time-between-eviction-runs-millis=60000
    #配置一个连接在池中最小生存的时间,单位是毫秒
    spring.datasource.druid.min-evictable-idle-time-millis=300000
    #配置扩展插件:监控统计用的filter:stat 日志用的filter:log4j 防御sql注入的filter:wall
    spring.datasource.druid.filters=stat,wall
    spring.datasource.druid.filter.stat.log-slow-sql=true
    spring.datasource.druid.filter.stat.slow-sql-millis=2000
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    3.3 配置jpa

    #必须采用 jpa
    
    spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
    spring.jpa.hibernate.ddl-auto=update
    spring.jpa.show-sql=true
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    3.4 配置注册中心

    eureka.client.service-url.defaultZone: http://localhost:8761/eureka/
    eureka.instance.appname=transaction-manager
    eureka.instance.prefer-ip-address=true
    
    • 1
    • 2
    • 3

    3.5 配置LCN管理界面信息

    # 开启日志
    
    #tx-lcn.logger.enabled=true
    #logging.level.com.codingapi=debug
    
    # TM监听IP. 默认为 127.0.0.1
    
    tx-lcn.manager.host=127.0.0.1
    
    # TM监听Socket端口. 默认为 ${server.port} - 100
    
    tx-lcn.manager.port=8070
    
    # 心跳检测时间(ms). 默认为 300000
    
    tx-lcn.manager.heart-time=300000
    
    #  分布式事务执行总时间(ms). 默认为36000
    
    tx-lcn.manager.dtx-time=8000
    
    # 参数延迟删除时间单位ms  默认为dtx-time值
    
    tx-lcn.message.netty.attr-delay-time=${tx-lcn.manager.dtx-time}
    
    # 事务处理并发等级. 默认为机器逻辑核心数5倍
    
    tx-lcn.manager.concurrent-level=40
    
    # TM后台登陆密码,默认值为codingapi
    
    tx-lcn.manager.admin-key=123456
    
    # 分布式事务锁超时时间 默认为-1,当-1时会用tx-lcn.manager.dtx-time的时间
    
    tx-lcn.manager.dtx-lock-time=${tx-lcn.manager.dtx-time}
    
    #  雪花算法的sequence位长度,默认为12.
    
    tx-lcn.manager.seq-len=12
    
    # 异常回调开关。开启时请制定ex-url
    
    tx-lcn.manager.ex-url-enabled=false
    
    # 事务异常通知(任何http协议地址。未指定协议时,为TM提供内置功能接口)。默认是邮件通知
    
    tx-lcn.manager.ex-url=/provider/email-to/***@**.com
    
    # 开启日志,默认为false
    
    tx-lcn.logger.auto-commit=true
    tx-lcn.logger.enabled=true
    tx-lcn.logger.driver-class-name=${spring.datasource.druid.driver-class-name}
    tx-lcn.logger.jdbc-url=${spring.datasource.druid.url}
    tx-lcn.logger.username=${spring.datasource.druid.username}
    tx-lcn.logger.password=${spring.datasource.druid.password}
    logging.level.com.codingapi.txlcn=DEBUG
    
    • 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

    3.6 配置redis

    spring.redis.host=121.199.66.248
    spring.redis.port=6379
    spring.redis.timeout=5000
    spring.redis.jedis.pool.max-active=500
    # 连接池最大阻塞等待时间(使用负值表示没有限制)
    spring.redis.jedis.pool.max-wait=-1
    # 连接池中的最大空闲连接
    spring.redis.jedis.pool.max-idle=20
    # 连接池中的最小空闲连接
    spring.redis.jedis.pool.min-idle=5
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    @SpringBootApplication
    @EnableEurekaClient
    @EnableTransactionManagerServer  #服务器的一个注解
    public class TxLcnApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(TxLcnApplication.class,args);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    4 搭建client端
    4.1 导入依赖

    <dependency>
                <groupId>com.codingapi.txlcn</groupId>
                <artifactId>txlcn-tc</artifactId>
                <version>5.0.2.RELEASE</version>
            </dependency>
    
            <dependency>
                <groupId>com.codingapi.txlcn</groupId>
                <artifactId>txlcn-txmsg-netty</artifactId>
                <version>5.0.2.RELEASE</version>
            </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    4.2 在启动类上添加注解
    @EnableDistributedTransaction

    @SpringBootApplication
    @EnableEurekaClient
    @EnableFeignClients
    @EnableDistributedTransaction
    public class UserApplication {
        public static void main(String[] args) {
            SpringApplication.run(UserApplication.class,args);
        }
        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    4.3 添加我们的 yml文件配置

      datasource:
        druid:
          username: root
          password: root
          url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
          driver-class-name: com.mysql.cj.jdbc.Driver
          #初始化大小,最小,最大
          initial-size: 10
          min-idle: 10
          max-active: 100
          # 配置获取连接等待超时的时间
          max-wait: 6000
          # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位毫秒
          time-between-eviction-runs-millis: 60000
          # 配置一个连接在池中最小生存时间
          min-evictable-idle-time-millis: 300000
          validation-query: SELECT 1 FROM DUAL
          test-while-idle: true
          test-on-borrow: false
          test-on-return: false
      jpa:
        database-platform:
        hibernate:
          ddl-auto: update
        show-sql: true
    
    • 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

    5 父pom文件添加的依赖

    
            
            <dependency>
                <groupId>com.alibabagroupId>
                <artifactId>druid-spring-boot-starterartifactId>
                <version>1.1.22version>
            dependency>
    
    
            
            
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <version>8.0.21version>
            dependency>
    
           
            <dependency>
                <groupId>com.baomidougroupId>
                <artifactId>mybatis-plus-boot-starterartifactId>
                <version>3.3.2version>
            dependency>
            <dependency>
                <groupId>com.baomidougroupId>
                <artifactId>mybatis-plus-generatorartifactId>
                <version>3.3.2version>
            dependency>
    
        
          
    
            
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-data-jpaartifactId>
                <version>2.4.5version>
            dependency>
    
            
            <dependency>
                <groupId>org.projectlombokgroupId>
                <artifactId>lombokartifactId>
                <optional>trueoptional>
            dependency>
    
            
            <dependency>
                <groupId>com.alibabagroupId>
                <artifactId>fastjsonartifactId>
                <version>1.2.75version>
            dependency>
    
            
            <dependency>
                <groupId>org.apache.commonsgroupId>
                <artifactId>commons-lang3artifactId>
                <version>3.12.0version>
            dependency>
    
            
            <dependency>
                <groupId>log4jgroupId>
                <artifactId>log4jartifactId>
                <version>1.2.17version>
            dependency>
    
            
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-data-redisartifactId>
                <version>2.5.2version>
                <exclusions>
                    <exclusion>
                        <groupId>redis.clientsgroupId>
                        <artifactId>jedisartifactId>
                    exclusion>
                    <exclusion>
                        <artifactId>lettuce-coreartifactId>
                        <groupId>io.lettucegroupId>
                    exclusion>
                exclusions>
            dependency>
    
    
            <dependency>
                <groupId>redis.clientsgroupId>
                <artifactId>jedisartifactId>
            dependency>
            
            <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-pool2artifactId>
            dependency>
    
    
    
    • 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
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100

    6、启动 TxLcnApplication

    5.1 首先启动注册中心eureka
    5.2 在启动config
    5.3 在启动LCN服务
    5.4 访问lcn地址:http://本地地址:lcn端口
    密码为: tx-lcn.manager.admin-key=123456

    image.png

    image.png

    tm主机Ip :当前server地址,客户端连接服务器端的地址
    tm事务消息接口:端口
    已注册的TC :表示有哪些客户端链接了的服务控制了事务;
    异常记录:表示事务流报错的基本日志信息
    系统日志:表示报错的后记录的日志

    四 创建客户端

    我们这里以basic 和 order作为实例
    3.1 basic 整合
    1 首先basic 导入依赖

    <dependency>
        <groupId>com.codingapi.txlcn</groupId>
        <artifactId>txlcn-tc</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>
    
    <dependency>
        <groupId>com.codingapi.txlcn</groupId>
        <artifactId>txlcn-txmsg-netty</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    2、配置yml

    tx-lcn:
      client:
        manager-address: 127.0.0.1:8070
      ribbon:
        loadbalancer:
          dtx:
            enabled: true
      logger:
        enabled: true
        driver-class-name: com.mysql.cj.jdbc.Driver
        jdbc-url: jdbc:mysql://211.149.142.20:3306/hsp_dev1?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
        username: root
        password: 123456
    logging:
      level:
        com:
          codingapi:
            txlcn: DEBUG
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    3、启动类加上注解
    加上 @EnableDistributedTransaction 注解

    @SpringBootApplication
    @EnableEurekaClient
    @EnableFeignClients
    @EnableDistributedTransaction
    public class BasicApplication {
        public static void main(String[] args) {
            SpringApplication.run(BasicApplication.class,args);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    4、编写service代码
    在需要的方法上加上 :
    @LcnTransaction 分布式事务@Transactional 本地事务

    @LcnTransaction
    @Transactional
    public Object insert(){
        System.out.println("==========txuser=============");
        int i = (int)(Math.random()*10000 + 1);
        TxUser txUser = new TxUser();
        txUser.setId(i+"");
        txUser.setName("张三");
        txUser.setPwd("123456");
    
        iTxUser.save(txUser);
        iOrderFeign.txRole();
    
        System.out.println("==========txuser=============");
        //throw new NullPointerException("LCN EXCEPTION......");
        return new String("成功!!!");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    3.2 order整合
    与basic 前面四个步骤一样,在这里不在讲解
    5、编写feign

    @FeignClient(value = "order",fallbackFactory = OrderFallBackFactory.class)
    public interface IOrderFeign {
        @RequestMapping(value = "/order/txRole")
        public String txRole();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    6、启动注册中心eureka 、 config 、lcnserver、basice、order服务
    通过basice调用order

    image.png

    测试事务

    四、总结

    注意事项 :LCN服务的事务需要在service编写

  • 相关阅读:
    Cortex-M架构MCU位带操作最详细解析(主要以STM32为例,包括判断哪些MCU可用)
    NC65 sql server 报数据库“xxx”事务日志已满 的解决方案。
    空间滤波-高斯低通滤波器
    基于Java汽车服务商城系统 设计实现(源码+lw+部署文档+讲解等)
    Linux系统上搭建Java的运行环境,并且部署JavaWeb程序
    做对这 6 件事,提高软件测试的能力?
    数据库的概念和sql语句
    java计算机毕业设计汇美食电子商城MyBatis+系统+LW文档+源码+调试部署
    nvm报错获取 ‘https://npm.taobao.org/mirrors/node/index.json‘ 时失败
    视觉语言跨模态特征语义相似度计算改进--表征空间维度语义依赖感知聚合算法 ACM MM
  • 原文地址:https://blog.csdn.net/yc_Cabbage/article/details/126338656