分布式事务实现要么成功、要么失败
操作步骤是:1、引入jar,2、编码中指定事务类型。3、配置相关参数。4、通过SPI的方式加载。

1、编写配置文件

image.pngimage.png

2、引入jar包

引入三个中其中之一的jar包就可以了

  1. <!-- XA模式-->
  2. <dependency>
  3. <groupId>org.apache.shardingsphere</groupId>
  4. <artifactId>sharding-transaction-xa-core</artifactId>
  5. </dependency>
  6. <!--Saga模式-->
  7. <dependency>
  8. <groupId>io.shardingsphere</groupId>
  9. <artifactId>sharding-transaction-base-saga</artifactId>
  10. </dependency>
  11. <!--Seata模式-->
  12. <dependency>
  13. <groupId>org.apache.shardingsphere</groupId>
  14. <artifactId>sharding-transaction-base-seata-at</artifactId>
  15. </dependency>

3、给Boot开启事物管理

image.png

  1. @EnableTransactionManagement
  2. /*如果是web环境则用main方法*/
  3. @SpringBootApplication
  4. public class RunBoot {
  5. }

4、添加事物、指定分布式的类型

image.png

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、测试结果

成功抛出异常
image.png

数据库都没有对root用户的数据进行存储(事物成功执行)
image.png image.png