微服务分布式事务 - Seata

Seata服务的安装和配置请点击这里

yml配置(需要参与分布式事务的微服务)

seata:
  # 是否开启spring-boot自动装配
  enabled: true
  application-id: ${spring.application.name}
  # 自定义事务分组名称,默认为:${spring.application.name}-seata-service-group
  tx-service-group: ${spring.application.name}
  # 是否开启数据源自动代理
  enable-auto-data-source-proxy: true
  data-source-proxy-mode: AT
  # 设置Seata服务的注册中心为nacos,以下相关配置需要和nacos中的相关配置保持一致
  registry:
    type: nacos
    nacos:
      application: serviceSeata
      server-addr: 1.116.1.203:8840
      namespace: d50a1a79-cf7c-4b95-ae2e-d0b4096a06dc
      group: SpringCloudAlibaba
      cluster: default
      userName: nacos账号
      password: nacos密码
  # 设置Seata服务的配置中心为nacos,以下相关配置需要和nacos中的相关配置保持一致
  config:
    type: nacos
    nacos:
      server-addr: 1.116.1.203:8840
      namespace: d50a1a79-cf7c-4b95-ae2e-d0b4096a06dc
      group: SpringCloudAlibaba
      dataId: seata.properties
      userName: nacos账号
      password: nacos密码

Java代码(@GlobalTransactional全局事务注解)

package com.springcloudalibaba.serviceUser.controller.buyer;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.mysql.jdbc.log.LogUtils;
import com.springcloudalibaba.basefeign.service.order.api.OrderFeign;
import com.springcloudalibaba.basefeign.service.order.vo.BuyerOrderVo;
import com.springcloudalibaba.basefeign.service.product.api.ProductFeign;
import com.springcloudalibaba.basefeign.service.product.vo.SellerProductVo;
import com.springcloudalibaba.bclass.base.BaseException;
import com.springcloudalibaba.bclass.base.BaseResult;
import com.springcloudalibaba.bclass.enums.SysStateEnum;
import com.springcloudalibaba.bclass.util.LoggerUtil;
import com.springcloudalibaba.serviceUser.entity.buyer.BuyerEntity;
import com.springcloudalibaba.serviceUser.entity.seller.SellerEntity;
import com.springcloudalibaba.serviceUser.service.buyer.BuyerService;
import com.springcloudalibaba.serviceUser.service.seller.SellerService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

/**
 * <p>
 * 买家信息 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/buyer")
public class BuyerController {
    
    
    @Resource
    private BuyerService buyerService;

    @Resource
    private SellerService sellerService;

    @Resource
    private ProductFeign productFeign;

    @Resource
    private OrderFeign orderFeign;

    /**
     * @描述 创建订单
     * @作者 [email protected]
     * @日期 2021/9/17 14:29
     */
    @PostMapping("createOrder")
    @GlobalTransactional
    public BaseResult<String> createOrder() {
    
    
        System.out.println("xid========================" + RootContext.getXID());
        // 扣库存(分布式事务)
        SellerProductVo sellerProductVo = new SellerProductVo();
        sellerProductVo.setId(1000000L);
        sellerProductVo.setStock(1);
        BaseResult<String> baseResultForChangeStock = productFeign.changeStock(sellerProductVo);
        if (!baseResultForChangeStock.isSuccess()) {
    
    
            throw new BaseException(baseResultForChangeStock.getMsg());
        }

        // 创建订单(分布式事务)
        BuyerOrderVo buyerOrderVo = new BuyerOrderVo();
        buyerOrderVo.setCreateTime(new Date());
        buyerOrderVo.setCode("order1000000");
        buyerOrderVo.setProductId(1000000L);
        buyerOrderVo.setPayState(SysStateEnum.ORDER_STATE_ING.getValue());
        BaseResult<String> baseResultForCreateOrder = orderFeign.createOrder(buyerOrderVo);
        if (!baseResultForCreateOrder.isSuccess()) {
    
    
            throw new BaseException(baseResultForChangeStock.getMsg());
        }

        // 扣减账户金额(本地事务)
        boolean updateBuyerFlag = buyerService.update(new UpdateWrapper<BuyerEntity>().set("grade", 0).eq("account", "31011225"));
        if (!updateBuyerFlag) {
    
    
            throw new BaseException("扣减账户金额失败");
        }
        // 测试异常是否触发全局事务的回滚
        System.out.println(0/0);
        return new BaseResult<String>().success(buyerOrderVo.getCode());
    }
}

猜你喜欢

转载自blog.csdn.net/qq_30818545/article/details/121549694