分布式事务

微服务中经常遇到操作多个数据库的场景,或者通过一个服务通过feign方式调用另一个服务,两个服务都有数据库写操作;这样就遇到了分布式事务Transaction的问题。

对于服务调用的场景,可以使用tx-lcn框架,在线文档可以参考:

https://www.codingapi.com/docs/txlcn-preface/

这里只简单的介绍其中一种解决方法,用于两个服务都有事务的场景,对于只有一个服务使用事务另一个不需要使用事务的情况可以使用TCC模式。

1、tx-manager 服务启动

pom.xml中添加依赖:

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

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

<!--tm-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>

启动类上添加注解:

@EnableTransactionManagerServer

配置文件:

server.port=8888

spring.application.name=lcn-tm

# TM 事务管理器使用的数据库

spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/tx-manager?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=root

# tx 事务管理器使用 redis 配置

spring.redis.host=127.0.0.1

spring.redis.port=6379

spring.redis.database=10

# tx 日志数据库配置

tx-lcn.logger.driver-class-name=com.mysql.cj.jdbc.Driver tx-lcn.logger.jdbc-url=jdbc:mysql://127.0.0.1:3306/tx-manager?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC tx-lcn.logger.username=root tx-lcn.logger.password=root

# TM 事务管理器管理平台登录密码

tx-lcn.manager.admin-key=alice

# 开启 TM 日志

tx-lcn.logger.enabled=true

登录tx 后台管理平台,

http://localhost:8888/

输入密码alice,登录成功后看到如下界面:

 

2、事务发起方服务所在项目的启动类上添加注解:

@EnableDistributedTransaction

事务方法上添加注解:

@LcnTransaction

@Transactional(rollbackFor = Exception.class)

pom.xml 文件中添加依赖如下:

<dependency>

    <groupId>com.codingapi.txlcn</groupId>

    <artifactId>txlcn-tc</artifactId>

</dependency>

<dependency>

    <groupId>com.codingapi.txlcn</groupId>

    <artifactId>txlcn-txmsg-netty</artifactId>

</dependency>

3、事务参与方服务所在项目的启动类上添加注解:

@EnableDistributedTransaction

方法上

@LcnTransaction

@Transactional(rollbackFor = Exception.class)

pom.xml中添加依赖:

<dependency>

    <groupId>com.codingapi.txlcn</groupId>

    <artifactId>txlcn-tc</artifactId>

</dependency>

<dependency>

    <groupId>com.codingapi.txlcn</groupId>

    <artifactId>txlcn-txmsg-netty</artifactId>

</dependency>

4、事务发起方和参与方的配置文件application.properties都添加如下配置

tx-lcn.client.manager-address=127.0.0.1:8988

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值