在 上一篇文章,我们构建会员业务服务,本文将加入分布式事务。
要加入对 TX-LCN 分布式事务的支持, 需要在三个业务项目中加入
依赖库
在 pom.xml 文件中加入依赖项:
1 2 3 4 5 6 7 8 9 10 11 12 13
| <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>
|
启动分布式事务支持
在启动程序(类)中,加入注解: @EnableDistributedTransaction, 例如在订单业务中的启动类加入:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @SpringBootApplication @EnableDistributedTransaction public class TxOrderApplication {
public static void main(String[] args) {
SpringApplication.run(TxOrderApplication.class, args); }
@Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } }
|
在每个业务方法中加入分布式事务
在业务方法中加入注解: @LcnTransaction 。 类如在订单业务中加入:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @LcnTransaction @Transactional public void confimOrder(String prod, Double amount, Integer allCount) {
OrderMaster order = new OrderMaster(); order.setProduct(prod); order.setAmount(amount); order.setAllCount(allCount);
orderRepos.save(order);
accountHistoryClient.handleOrder(order);
storeMasterClient.handleOrder(order);
}
|
修改配置文件
在每个业务项目的 application.yml 添加如下的内容:
1 2 3
| tx-lcn: client: manager-address: 127.0.0.1:8070
|