微服务中经常遇到操作多个数据库的场景,或者通过一个服务通过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 后台管理平台,
输入密码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