分布式事务实现要么成功、要么失败
操作步骤是:1、引入jar,2、编码中指定事务类型。3、配置相关参数。4、通过SPI的方式加载。
1、编写配置文件
2、引入jar包
引入三个中其中之一的jar包就可以了
<!-- XA模式-->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-transaction-xa-core</artifactId>
</dependency>
<!--Saga模式-->
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>sharding-transaction-base-saga</artifactId>
</dependency>
<!--Seata模式-->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-transaction-base-seata-at</artifactId>
</dependency>
3、给Boot开启事物管理
@EnableTransactionManagement
/*如果是web环境则用main方法*/
@SpringBootApplication
public class RunBoot {
}
4、添加事物、指定分布式的类型
package com.slin.test;
import com.slin.RunBoot;
import com.slin.entity.Position;
import com.slin.entity.PositionDetail;
import com.slin.repository.PositionDetailRepository;
import com.slin.repository.PositionRepository;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.apache.shardingsphere.transaction.core.TransactionTypeHolder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestEntityManager;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import javax.transaction.Transactional;
//通过它来启动
@RunWith(SpringRunner.class)
//通过RunBoot来创建boot容器
@SpringBootTest(classes = RunBoot.class)
public class XABaseTest {
@Resource
PositionRepository positionRepository;
@Resource
PositionDetailRepository positionDetailRepository;
@Test
@Transactional // 添加事物(在这里加相当于整个方法是一个整体)
//@ShardingTransactionType(TransactionType.XA)
public void test(){
//指明使用的事物类型XA、base这两种类型(指明是分布式的)
TransactionTypeHolder.set(TransactionType.XA);
for (int i=1;i<=5;i++){
Position position = new Position();
position.setName("root"+i);
position.setSalary("1000000");
position.setCity("beijing");
positionRepository.save(position);
if (i==3){
throw new RuntimeException("人为制造异常");
}
PositionDetail positionDetail = new PositionDetail();
positionDetail.setPid(position.getId());
positionDetail.setDescription("this is a root "+i);
positionDetailRepository.save(positionDetail);
}
}
}
5、测试结果
成功抛出异常
数据库都没有对root用户的数据进行存储(事物成功执行)