SpringCloud整合TX-LCN5.0.2使用LCN实现分布式事务(附源码)

框架介绍

LCN分布式事务框架其本身并不创建事务,而是基于对本地事务的协调从而达到事务一致性的效果

核心步骤
创建事务组
是指在事务发起方开始执行业务代码之前先调用TxManager创建事务组对象,然后拿到事务标示GroupId的过程。
添加事务组
添加事务组是指参与方在执行完业务方法以后,将该模块的事务信息添加通知给TxManager的操作。
关闭事务组
是指在发起方执行完业务代码以后,将发起方执行结果状态通知给TxManager的动作。当执行完关闭事务组的方法以后,TxManager将根据事务组信息来通知相应的参与模块提交或回滚事务。

事务控制原理
LCN事务控制原理是由事务模块TxClient下的代理连接池与TxManager的协调配合完成的事务协调控制。
TxClient的代理连接池实现了javax.sql.DataSource接口,并重写了close方法,事务模块在提交关闭以后TxClient连接池将执行"假关闭"操作,等待TxManager协调完成事务以后在关闭连接。

一、环境搭建:

SpringBoot+eureka+feign+redis+mysql
redis采用本地redis,mysql采用5.7版本

二、代码

代码结构:
SpringCloud整合TX-LCN5.0.2使用LCN实现分布式事务(附源码)_第1张图片
tx-manager是事务中间件,account-api是一个api,消费者调用生产者要用到,剩下的三个是注册中心、生产者和消费者

1、eureka:
SpringCloud整合TX-LCN5.0.2使用LCN实现分布式事务(附源码)_第2张图片
pom文件:

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.hand.txlcn</groupId>
    <artifactId>eureka-server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>eureka-server</name>
    <description>eureka-server</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

配置文件:

# 设置spring应用命名,可以自定义,非必要
spring.application.name=eureka-server
# 设置Eureka Server WEB控制台端口,自定义
server.port=8761

#是否将自己注册到Eureka-Server中,默认的为true
eureka.client.registerWithEureka=false
#是否从Eureka-Server中获取服务注册信息,默认为true
eureka.client.fetchRegistry=false

启动类:

package com.hand.txlcn.eureka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }

}

2、tx-manager
SpringCloud整合TX-LCN5.0.2使用LCN实现分布式事务(附源码)_第3张图片
pom文件:

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.hand.txlcn</groupId>
    <artifactId>tx-manager</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>tx-manager</name>
    <description>tx-manager</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.codingapi.txlcn</groupId>
            <artifactId>txlcn-tm</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

配置文件:
指定了tx-manager服务的相关参数,tx要用到redis,需要手动修改一下redis

server.port=7971
spring.application.name=tx-manager
#mysql
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/tx-manager?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=root

#TxManager Host Ip
tx-lcn.manager.host=127.0.0.1
#TxClient连接请求端口
tx-lcn.manager.port=8070
#心跳检测时间(ms)
tx-lcn.manager.heart-time=15000
#分布式事务执行总时间
tx-lcn.manager.dtx-time=30000
#参数延迟删除时间单位ms
tx-lcn.message.netty.attr-delay-time=10000
tx-lcn.manager.concurrent-level=128
#TM后台登陆密码,默认值为codingapi
tx-lcn.manager.admin-key=123456
logging.level.com.codingapi=debug
#开启日志,默认为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}
#redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=12345

搭建完成后在浏览器输入:http://localhost:7971
SpringCloud整合TX-LCN5.0.2使用LCN实现分布式事务(附源码)_第4张图片
输入密码:123456即可登录,密码在配置文件中配置,登录后效果图如下,目前还没客户端注册到tm中
SpringCloud整合TX-LCN5.0.2使用LCN实现分布式事务(附源码)_第5张图片
3、api:
SpringCloud整合TX-LCN5.0.2使用LCN实现分布式事务(附源码)_第6张图片
无配置文件

package com.hand.txlcn.account.api;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@RequestMapping("/api/account")
public interface AccountInterface {
    @GetMapping("/add-money")
    Boolean addMoney(@RequestParam("money") int money,
                     @RequestParam("user") String user);
}

package com.hand.txlcn.account.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account {
    private Integer id;
    private Integer money;
    private String user;
}

4、提供者:
提供者即事务参与者
SpringCloud整合TX-LCN5.0.2使用LCN实现分布式事务(附源码)_第7张图片
pom文件

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.hand.txlcn</groupId>
    <artifactId>bank-provider</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>bank-provider</name>
    <description>bank-provider</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.hand.txlcn</groupId>
            <artifactId>account-api</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!--tx-lcn配置-->
        <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-data-redis</artifactId>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

配置文件:

server.port=8080
spring.application.name=bank-provider
eureka.client.service-url.defaultZone=http://127.0.0.1:8761/eureka/
eureka.instance.prefer-ip-address=true
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/bank-provider?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=root
#lcn配置
tx-lcn.client.manager-address=127.0.0.1:8070
#是否开启日志记录,当开启以后需要配置对应logger的数据库连接配置信息
tx-lcn.logger.enabled=true
tx-lcn.logger.driver-class-name=${spring.datasource.driver-class-name}
tx-lcn.logger.jdbc-url=jdbc:mysql://127.0.0.1:3306/tx-manager?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true&allowPublicKeyRetrieval=true
tx-lcn.logger.username=root
tx-lcn.logger.password=root

controller:

package com.hand.txlcn.bank.provider.implement.web;
import com.hand.txlcn.account.api.AccountInterface;
import com.hand.txlcn.bank.provider.service.impl.AccountServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class ImplementController implements AccountInterface {
    @Autowired
    private AccountServiceImpl accountServiceImpl;

    @Override
    public Boolean addMoney(@RequestParam("money") int money,
                            @RequestParam("user") String user) {
        return accountServiceImpl.addMoney(money, user);
    }
}

service:

package com.hand.txlcn.bank.provider.service;

public interface AccountService {
     Boolean addMoney(int money, String user);
}

impl:

package com.hand.txlcn.bank.provider.service.impl;

import com.codingapi.txlcn.tc.annotation.DTXPropagation;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.hand.txlcn.account.domain.Account;
import com.hand.txlcn.bank.provider.mapper.AccountMapper;
import com.hand.txlcn.bank.provider.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountMapper accountMapper;

    @Override
    //事物的参与方
    @LcnTransaction(propagation = DTXPropagation.SUPPORTS)
    @Transactional
    public Boolean addMoney(int money, String user) {
        Account account = new Account();
        account.setMoney(money);
        account.setUser(user);
        accountMapper.addMoney(account);
        return true;
    }
}
mapper:

```java
package com.hand.txlcn.bank.provider.mapper;

import com.hand.txlcn.account.domain.Account;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Update;

@Mapper
public interface AccountMapper {

    @Update("update t_bank set money = money+#{money} where user = #{user}")
    int addMoney(Account account);
}

启动类:

```java
package com.hand.txlcn.bank.provider;
import com.codingapi.txlcn.tc.config.EnableDistributedTransaction;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@EnableDiscoveryClient
//开启分布式事务
@EnableDistributedTransaction
@SpringBootApplication
public class BankProviderApplication {

    public static void main(String[] args) {
        SpringApplication.run(BankProviderApplication.class, args);
    }

}

5、消费者
即事务发起者
SpringCloud整合TX-LCN5.0.2使用LCN实现分布式事务(附源码)_第8张图片
pom:

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.hand.txlcn</groupId>
    <artifactId>bank-consumer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>bank-consumer</name>
    <description>bank-consumer</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.hand.txlcn</groupId>
            <artifactId>account-api</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!--tx-lcn配置-->
        <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-data-redis</artifactId>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

配置文件:

server.port=8081
spring.application.name=bank-consumer
eureka.client.service-url.defaultZone=http://127.0.0.1:8761/eureka/
eureka.instance.prefer-ip-address=true
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/bank-consumer?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=root

#是否启动LCN负载均衡策略(优化选项,开启与否,功能不受影响)
tx-lcn.ribbon.loadbalancer.dtx.enabled=true
#是否开启日志记录,当开启以后需要配置对应logger的数据库连接配置信息
tx-lcn.logger.enabled=true
tx-lcn.logger.driver-class-name=${spring.datasource.driver-class-name}
tx-lcn.logger.jdbc-url=jdbc:mysql://127.0.0.1:3306/tx-manager?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true&allowPublicKeyRetrieval=true
tx-lcn.logger.username=root
tx-lcn.logger.password=root
#redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=12345

配置类:

package com.hand.txlcn.bank.config;

import com.codingapi.txlcn.common.exception.TxClientException;
import com.codingapi.txlcn.common.runner.TxLcnApplicationRunner;
import com.codingapi.txlcn.common.util.ApplicationInformation;
import com.codingapi.txlcn.common.util.id.ModIdProvider;
import com.codingapi.txlcn.logger.TxLoggerConfiguration;
import com.codingapi.txlcn.tc.config.EnableDistributedTransaction;
import com.codingapi.txlcn.tc.config.TxClientConfig;
import com.codingapi.txlcn.tracing.TracingAutoConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Description:
 * Date: 1/19/19
 *
 * @author ujued
 * @see EnableDistributedTransaction
 */
@Configuration
@ComponentScan(
        excludeFilters = @ComponentScan.Filter(
                type = FilterType.ASPECTJ, pattern = "com.codingapi.txlcn.tc.core.transaction.txc..*"
        )
)
@Import({TxLoggerConfiguration.class, TracingAutoConfiguration.class})
public class TCAutoConfiguration {

    private static final String REDIS_TM_LIST = "tm.instances";

    @Bean
    public ApplicationRunner txLcnApplicationRunner(ApplicationContext applicationContext) {
        return new TxLcnApplicationRunner(applicationContext);
    }

    @Bean
    @ConditionalOnMissingBean
    public ModIdProvider modIdProvider(ConfigurableEnvironment environment,
                                       @Autowired(required = false) ServerProperties serverProperties) {
        return () -> ApplicationInformation.modId(environment, serverProperties);
    }

    @Bean
    @ConfigurationProperties(prefix = "tx-lcn.client")
    public TxClientConfig txClientConfig(@Autowired StringRedisTemplate stringRedisTemplate) throws TxClientException {
        TxClientConfig txClientConfig = new TxClientConfig();
        List<String> managerAddress = stringRedisTemplate.opsForHash().entries(REDIS_TM_LIST).entrySet().stream()
                .map(entry -> entry.getKey().toString()).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(managerAddress)) {
            throw new TxClientException("在redis没有找到可用的tx-manager地址");
        }
        txClientConfig.setManagerAddress(managerAddress);
        return txClientConfig;
    }
}

feign:

package com.hand.txlcn.bank.consumer.client;

import com.hand.txlcn.account.api.AccountInterface;
import org.springframework.cloud.openfeign.FeignClient;

@FeignClient(value = "bank-provider")
public interface BankProviderClient extends AccountInterface {
}

controller:

package com.hand.txlcn.bank.consumer.controller;

import com.hand.txlcn.bank.consumer.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class AccountController {
    @Autowired
    private AccountService accountService;

    @GetMapping("/transferAccounts")
    public Boolean transferAccounts(@RequestParam int money,
                                    @RequestParam String userFrom,
                                    @RequestParam String userTo) {
        return accountService.transferAccounts(money, userFrom, userTo);
    }

}

service:

package com.hand.txlcn.bank.consumer.service;

public interface AccountService {
    Boolean transferAccounts(int money, String userFrom, String userTo);
}

impl:

package com.hand.txlcn.bank.consumer.service.impl;

import com.codingapi.txlcn.tc.annotation.DTXPropagation;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.hand.txlcn.account.domain.Account;
import com.hand.txlcn.bank.consumer.client.BankProviderClient;
import com.hand.txlcn.bank.consumer.mapper.AccountMapper;
import com.hand.txlcn.bank.consumer.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private BankProviderClient bankProviderClient;

    @Override
    @LcnTransaction(propagation = DTXPropagation.REQUIRED) //分布式事务注解
    @Transactional
    public Boolean transferAccounts(int money, String userFrom, String userTo) {
        Account myAccount = new Account();
        myAccount.setMoney(money);
        myAccount.setUser(userFrom);
        accountMapper.subMoney(myAccount);
        bankProviderClient.addMoney(money, userTo);//调用bank-provider服务
        //int i = 1 / 0;
        return true;
    }
}

mapper:

package com.hand.txlcn.bank.consumer.mapper;

import com.hand.txlcn.account.domain.Account;
import org.apache.ibatis.annotations.Update;

public interface AccountMapper {
    @Update("update t_bank set money = money-#{money} where user = #{user}")
    int subMoney(Account account);
}

启动类:

package com.hand.txlcn.bank.consumer;

import com.codingapi.txlcn.tc.config.EnableDistributedTransaction;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@MapperScan("com.hand.txlcn.bank.consumer.mapper")
@EnableDiscoveryClient
@EnableFeignClients
//开启分布式事务
@EnableDistributedTransaction
@SpringBootApplication
public class BankConsumerApplication {

	public static void main(String[] args) {
		SpringApplication.run(BankConsumerApplication.class, args);
	}

}

三、表结构

SpringCloud整合TX-LCN5.0.2使用LCN实现分布式事务(附源码)_第9张图片

CREATE TABLE `t_logger` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `group_id` varchar(64) NOT NULL,
  `unit_id` varchar(32) NOT NULL,
  `tag` varchar(50) NOT NULL,
  `content` varchar(1024) NOT NULL,
  `create_time` varchar(30) NOT NULL,
  `app_name` varchar(128) NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;


CREATE TABLE `t_tx_exception` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `group_id` varchar(64) DEFAULT NULL,
  `unit_id` varchar(32) DEFAULT NULL,
  `mod_id` varchar(128) DEFAULT NULL,
  `transaction_state` tinyint(4) DEFAULT NULL,
  `registrar` tinyint(4) DEFAULT NULL,
  `remark` varchar(4096) DEFAULT NULL,
  `ex_state` tinyint(4) DEFAULT NULL COMMENT '0 未解决 1已解决',
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC;

建立两个数据库,分别对应两个微服务:
每个数据库建立一张表:

CREATE TABLE `t_bank` (
  `id` int(11) DEFAULT NULL,
  `money` int(11) DEFAULT NULL,
  `user` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

在两个数据库的t_bank表中各插入一条数据:

INSERT INTO bank-consumer.t_bank (id, money, user) VALUES (‘1’, ‘100’, ‘a’);

INSERT INTO bank-provider.t_bank (id, money, user) VALUES (‘1’, ‘100’, ‘b’);

然后依次启动,eureka,tx-manager,bank-provider,bank-consumer
SpringCloud整合TX-LCN5.0.2使用LCN实现分布式事务(附源码)_第10张图片
SpringCloud整合TX-LCN5.0.2使用LCN实现分布式事务(附源码)_第11张图片
SpringCloud整合TX-LCN5.0.2使用LCN实现分布式事务(附源码)_第12张图片

四、分布式事务效果实现

现在模拟a给b转账,a和b数据库都是100块钱
模拟转账代码执行后报错报错,正常事务会回滚,转账前后a和b的钱不变
SpringCloud整合TX-LCN5.0.2使用LCN实现分布式事务(附源码)_第13张图片
转账前:
在这里插入图片描述
在这里插入图片描述
转账:
SpringCloud整合TX-LCN5.0.2使用LCN实现分布式事务(附源码)_第14张图片
转账后:
SpringCloud整合TX-LCN5.0.2使用LCN实现分布式事务(附源码)_第15张图片
SpringCloud整合TX-LCN5.0.2使用LCN实现分布式事务(附源码)_第16张图片
SpringCloud整合TX-LCN5.0.2使用LCN实现分布式事务(附源码)_第17张图片
a和b的账户金额没有变化,证明分布式事务有效果

现在把报错代码注释掉:
SpringCloud整合TX-LCN5.0.2使用LCN实现分布式事务(附源码)_第18张图片
继续用刚才的postman模拟一下转账:
转账后的效果如下:
SpringCloud整合TX-LCN5.0.2使用LCN实现分布式事务(附源码)_第19张图片
SpringCloud整合TX-LCN5.0.2使用LCN实现分布式事务(附源码)_第20张图片
SpringCloud整合TX-LCN5.0.2使用LCN实现分布式事务(附源码)_第21张图片
至此,分布式事务实现完毕,源码请从这里下载:
https://github.com/liqiang321/lcn.git

你可能感兴趣的:(分布式)