【SpringCloud系列】 分布式事务-LCN

简介: 一、什么是分布式事务分布式事务是指事务的参与者、支持事务的服务器、资源服务器以及事务管理器分别位于不同的分布式系统的不同节点之上。二,TX-LENTX-LCN分布式事务框架,LCN并不生产事务,LCN只是本地事务的协调工,LCN是一个高性能的分布式事务框架,兼容dubbo、springcloud框架,支持RPC框架拓展,支持各种ORM框架、NoSQL、负载均衡、事务补偿特性:  1、一致性,通过TxManager协调控制与事务补偿机制确保数据一致性  2、易用性,仅需要在业务方

 一、什么是分布式事务

 

分布式事务是指事务的参与者支持事务的服务器、资源服务器以及事务管理器分别位于不同的分布式系统的不同节点之上。

二,TX-LEN

TX-LCN分布式事务框架,LCN并不生产事务,LCN只是本地事务的协调工,LCN是一个高性能的分布式事务框架,兼容dubbo、springcloud框架,支持RPC框架拓展,支持各种ORM框架、NoSQL、负载均衡、事务补偿

特性:

  1、一致性,通过TxManager协调控制与事务补偿机制确保数据一致性

  2、易用性,仅需要在业务方法上添加@TxTransaction注解即可

  3、高可用,项目模块不仅可高可用部署,事务协调器也可集群化部署

  4、扩展性,支持各种RPC框架扩展,支持通讯协议与事务模式扩展

TxManager 原理

image.gif编辑

三,TxManager 使用方法

1,创建数据库、表

    1. 创建MySQL数据库, 名称为:tx-manager(直接选择在自己的数据库下面创建表就行了,可以不用单独创建)
    2. 创建数据表:t_tx_exception
    CREATE TABLE `t_tx_exception`  (
      `id` bigint(20) NOT NULL AUTO_INCREMENT,
      `group_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
      `unit_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
      `mod_id` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
      `transaction_state` tinyint(4) NULL DEFAULT NULL,
      `registrar` tinyint(4) NULL DEFAULT NULL,
      `remark` varchar(4096) NULL DEFAULT  NULL,
      `ex_state` tinyint(4) NULL DEFAULT NULL COMMENT '0 未解决 1已解决',
      `create_time` datetime NULL DEFAULT NULL,
      PRIMARY KEY (`id`) USING BTREE
    ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

    image.gif

    2,下载官方项目

    下载官网提供的最新版的TM项目,修改配置文件(PS:由于官网的下载地址打不开,我们去GitHub上面下载例子:https://github.com/codingapi/txlcn-demo),参考txlcn-demo-tm工程,在我们之前的项目下面创建一个springboot项目叫txlcn-tm

    image.gif编辑

    3.修改pom文件

    创建好springboot项目后,参照例子修改pom.xml文件

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>cn.huanzi.qch.txlcn</groupId>
        <artifactId>txlcn-tm</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>txlcn-tm</name>
        <description>Tx-Manager(TM),TX-LCN分布式事务框架的独立服务</description>
        <!--继承信息-->
        <parent>
            <groupId>cn.huanzi.qch</groupId>
            <artifactId>parent</artifactId>
            <version>1.0.0</version>
        </parent>
        <dependencies>
            <!-- 参照例子引入需要的依赖jar -->
            <dependency>
                <groupId>com.codingapi.txlcn</groupId>
                <artifactId>txlcn-tm</artifactId>
                <version>5.0.2.RELEASE</version>
            </dependency>
            <!-- text报错,添加一下依赖-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
        <!-- 构建工具 -->
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
            <finalName>txlcn-tm</finalName>
        </build>
    </project>

    image.gif

    4,修改配置

    参照官网修改配置文件,详细的TM配置请戳:https://www.txlcn.org/zh-cn/docs/setting/manager.html,开发阶段最好开启日志,并设置为debug等级,这样方便追踪排查问题

    5,添加注解

    在启动类添加注解 @EnableTransactionManagerServer
    import com.codingapi.txlcn.tm.config.EnableTransactionManagerServer;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    @SpringBootApplication
    @EnableTransactionManagerServer
    public class TxlcnTmApplication {
        public static void main(String[] args) {
            SpringApplication.run(TxlcnTmApplication.class, args);
        }
    }

    image.gif

    6,启动

    把我们的Redis服务运行起来,然后启动txlcn-tm,启动成功后访问tm后台管理系统,使用默认密码登录(可以配置登录密码),访问 http://127.0.0.1:7970/admin/index.html进入管理后台,默认密码是codingapi,我们这里配置了123456

      启动TM之前记得先启动我们的Redis服务,到这里,我们的tm搭建成功,更多TM介绍,请看官网TM管理手册:https://www.txlcn.org/zh-cn/docs/manageradmin.html

    四,Tx-Client

    4.1 添加pom依赖

    <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>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-jdbc</artifactId>
            </dependency>

    image.gif

    4.2 配置文件

    # 是否启动LCN负载均衡策略(优化选项,开启与否,功能不受影响)
    tx-lcn.ribbon.loadbalancer.dtx.enabled=true
    # 默认之配置为TM的本机默认端口
    tx-lcn.client.manager-address=127.0.0.1:8070
    # 开启日志,默认为false
    tx-lcn.logger.enabled=true
    tx-lcn.logger.driver-class-name=${spring.datasource.driver-class-name}
    tx-lcn.logger.jdbc-url=${spring.datasource.url}
    tx-lcn.logger.username=${spring.datasource.username}
    tx-lcn.logger.password=${spring.datasource.password}
    logging.level.com.codingapi.txlcn=DEBUG

    image.gif

    4.3 在启动类上使用 @EnableDistributedTransaction

    //省略其他代码...
    @EnableDistributedTransaction
    public class MyspringbootApplication {
        public static void main(String[] args) {
            SpringApplication.run(MyspringbootApplication.class, args);
        }
    }

    image.gif

    4.4 @LcnTransaction

    在提交本地事务的地方添加@LcnTransaction,分布式事务注解,PS:@LcnTransaction的target是在方法上的,@Target({ElementType.METHOD})

    4.5 测试

    我们挑选之前的两个项目myspringboot、springdatejpa,按照步骤设置成TC,并且在两个TC添加测试接口,

    4.5.1   myspringboot  controller

    /**
         * 测试分布式事务
         */
        @GetMapping("feign/save")
        Result<UserVo> save(UserVo userVo){
            //模拟数据
            Description description = new Description();
            description.setUserId("111");
            description.setDescription("测试用户描述");
            Result<Description> save = descriptionService.save(description);
            System.out.println(save);
            return null;
        }

    image.gif

    4.5.2 myspringboot  service

    @Override
        @LcnTransaction//分布式事务
        @Transactional //本地事务
        public Result<Description> save(Description description) {
            UserVo userVo = new UserVo();
            userVo.setUsername("huanzi");
            userVo.setPassword("123");
            //调用springdatejpa服务保存userVo
            Result<UserVo>  result = myspringbootFeign.save(userVo);
            System.out.println(result);
            //myspringboot本地服务保存description
            Description save = descriptionRepository.save(description);
            System.out.println(save);
            //模拟发生异常
            throw new RuntimeException("business code error");
        }

    image.gif

    feign

    @FeignClient(name = "springdatejpa", path = "/user/",fallback = MyspringbootFeignFallback.class,fallbackFactory = MyspringbootFeignFallbackFactory.class)
    public interface MyspringbootFeign {
        @RequestMapping(value = "save")
        Result<UserVo> save(@RequestBody UserVo userVo);
    }

    image.gif

    springdatejpa  项目

      这个原先就已经有对应的save接口,其他的代码我们就不贴了,在UserServiceImpl类重写save方法,在save方法上添加@LcnTransaction注解

    @LcnTransaction//分布式事务
        @Transactional //本地事务
        @Override
        public Result<UserVo> save(UserVo entity) {
            User user = userRepository.save(FastCopy.copy(entity, User.class));
            return Result.of(FastCopy.copy(user, UserVo.class));
        }

    image.gif

    到这里,就配置结束了,


    相关文章
    |
    9天前
    |
    关系型数据库 MySQL 数据库
    SpringCloud2023中使用Seata解决分布式事务
    对于分布式系统而言,需要保证分布式系统中的数据一致性,保证数据在子系统中始终保持一致,避免业务出现问题。分布式系统中对数据的操作要么一起成功,要么一起失败,必须是一个整体性的事务。Seata简化了这个使用过程。
    15 2
    |
    28天前
    |
    资源调度 Java 调度
    Spring Cloud Alibaba 集成分布式定时任务调度功能
    Spring Cloud Alibaba 发布了 Scheduling 任务调度模块 [#3732]提供了一套开源、轻量级、高可用的定时任务解决方案,帮助您快速开发微服务体系下的分布式定时任务。
    14211 19
    |
    1天前
    |
    Java 应用服务中间件 数据库
    SpringCloud:服务保护和分布式事务详解
    SpringCloud:服务保护和分布式事务详解
    11 0
    |
    1月前
    |
    消息中间件 Java 开发者
    Spring Cloud微服务框架:构建高可用、分布式系统的现代架构
    Spring Cloud是一个开源的微服务框架,旨在帮助开发者快速构建在分布式系统环境中运行的服务。它提供了一系列工具,用于在分布式系统中配置、服务发现、断路器、智能路由、微代理、控制总线、一次性令牌、全局锁、领导选举、分布式会话、集群状态等领域的支持。
    119 5
    |
    1月前
    |
    存储 安全 Java
    实现基于Spring Cloud的分布式配置管理
    实现基于Spring Cloud的分布式配置管理
    |
    1月前
    |
    消息中间件 负载均衡 Java
    Java和Spring Cloud构建分布式系统
    Java和Spring Cloud构建分布式系统
    |
    1月前
    |
    负载均衡 Java 开发者
    Spring Cloud实战:构建分布式系统解决方案
    Spring Cloud实战:构建分布式系统解决方案
    |
    2月前
    |
    负载均衡 安全 Java
    SpringCloud——分布式为什么越来越热门
    SpringCloud——分布式为什么越来越热门
    |
    2月前
    |
    存储 搜索推荐 Java
    微服务SpringCloud ES分布式全文搜索引擎简介 下载安装及简单操作入门
    微服务SpringCloud ES分布式全文搜索引擎简介 下载安装及简单操作入门
    41 2
    |
    2月前
    |
    Java 数据库 开发者
    深入解析 Spring Cloud Seata:分布式事务的全面指南
    深入解析 Spring Cloud Seata:分布式事务的全面指南
    129 1

    热门文章

    最新文章