首頁 > 軟體

springboot整合shardingsphere和seata實現分散式事務的實踐

2022-07-26 14:03:06

各個框架版本資訊

  • springboot: 2.1.3
  • springcloud: Greenwich.RELEASE
  • seata: 1.0.0
  • shardingsphere:4.0.1

maven 依賴

       <dependency>
        <!--<groupId>io.shardingsphere</groupId>-->
        <groupId>org.apache.shardingsphere</groupId>
        <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
    </dependency>
    <!--sharding-jdbc 4.0.0 以後版本不能加starter 會導致啟動資料來源衝突-->
    <!--<dependency>-->
        <!--<groupId>com.alibaba</groupId>-->
        <!--<artifactId>druid-spring-boot-starter</artifactId>-->
    <!--</dependency>-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
    </dependency>

    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
        <exclusions>
            <exclusion>
                <groupId>io.seata</groupId>
                <artifactId>seata-all</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>io.seata</groupId>
        <artifactId>seata-all</artifactId>
        <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.shardingsphere</groupId>
        <artifactId>sharding-transaction-base-seata-at</artifactId>
    </dependency>

需要增加的切面類

@Component
@Aspect
@Slf4j
public class SeataTransactionalAspect {
       @Before("execution(* com.XXX.dao.*.*(..))")
        public void before(JoinPoint joinPoint) throws TransactionException {
            MethodSignature signature = (MethodSignature)joinPoint.getSignature();
            Method method = signature.getMethod();
            log.info("攔截到需要分散式事務的方法," + method.getName());

        if(StringUtils.startsWithAny(method.getName(),"insert","save"
                ,"update","delete")){
            TransactionTypeHolder.set(TransactionType.BASE);
        }
    }
}

ProductServiceImpl程式碼

@Service
public class ProductServiceImpl implements ProductService {

    @Resource
    UserFeignClient userFeignClient;

    @Resource
    ProductDao productDao;
    
    @Override
    @GlobalTransactional(name="zhjy-product-tx-group",rollbackFor = Exception.class)
    public void createProduct(Product product) {
        productDao.insertProduct(product);
        ProductDesc proDesc = new ProductDesc();
        proDesc.setProductDesc(product.getProductDesc());
        proDesc.setStoreId(product.getStoreId());
        proDesc.setProductId(product.getProductId());
        productDao.insertProductDesc(proDesc);
//        if(product.getProductName().endsWith("5")){
//            int i = 1/0;
//        }
//        int j = 1/0;
        User user = new User();
        user.setAge(product.getPrice().intValue());
        user.setUserName(product.getProductName());
        user.setRealName(product.getProductName());
        String msg = userFeignClient.saveUser(user);
        //由於開啟了服務呼叫降級,所以需要統一返回錯誤碼,根據錯誤碼主動丟擲異常,讓seata回滾事務
        if(msg.equals("新增使用者失敗")){
             int i = 1/0;
        }
    }
 }

UserFeignClient程式碼

@FeignClient(name="service-user",fallbackFactory =UserFeignClientFallbackFactory.class)
public interface UserFeignClient {
    @GetMapping("/user/getUserById")
    @ResponseBody
    String getUserById(@RequestParam("id") Integer id);

    @GetMapping("/user/getUserByIdWithPathVariable/{id}")
    @ResponseBody
    String getUserByIdWithPathVariable(@PathVariable("id") Integer id);

    @PostMapping("/user/saveUser")
    @ResponseBody
    String saveUser(@RequestBody User user );

}

User服務 UserController程式碼

@RestController
@Slf4j
@RefreshScope
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/user/saveUser")
    @ResponseBody
    public String saveUser(@RequestBody User user) {
        userService.saveUser(user.getUserName(),user.getRealName(),user.getAge());

//        if(user.getAge()>5){
            int i = 1/0;
//        }
        return "sucess";
    }
}

UserServiceImpl程式碼

@Service
public class UserServiceImpl implements UserService {    
    @Resource
    UserDao userDao;

    @Override
    public void saveUser(String userName, String realName, Integer age) {
        userDao.insertUser(userName,realName,age);
    }

}

到此這篇關於springboot整合shardingsphere和seata實現分散式事務的實踐的文章就介紹到這了,更多相關springboot 分散式事務內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com