springboot 使用rocketmq实现简单的TCC

商品微服务

商品扣减库存请求体

java 复制代码
@Data
public class GoodsTccRequest {

    private List<Integer> skuIds;//商品售卖id

    private List<Integer> quantitys;//数量

    private String orderId;//订单号
}

商品TCC service

java 复制代码
public interface GoodsTccService {

    /**
     * 订单feign调用扣减库存时使用
     * */
    Integer tryStock(GoodsTccRequest request);//生成冻结库存记录,商品库存=商品库存-冻结库存,冻结库存状态=try

    /**
     * 监听MQ调用该方法,修改冻结状态
     * */
    Integer commitStock(String orderId);//冻结库存状态=commit


    /**
     * 监听MQ调用该方法,把冻结的库存加上去
     * */
    Integer cancelStock(String orderId);//冻结库存状态=cancle,商品库存=商品库存+冻结库存
}

tcc相关的监听器

java 复制代码
@Slf4j
@Service
@RocketMQMessageListener(consumerGroup = "goods_service_stock", topic = "order_create",messageModel= CLUSTERING,consumeThreadMax = 1)//"goods_change"
public class GoodsTccStockListener implements RocketMQListener<String>{

    @Resource
    private GoodsTccService goodsTccService;


    /*
    *监听商品tcc,执行tcc commit或者cancel
    * **/
    @Override
    public void onMessage(String body) {
        log.info("商品库存监听MQ消费 body {} ",body);

        JSONObject jsonObject = JSON.parseObject(body);
        String orderId = jsonObject.getString("orderId");
        String result = jsonObject.getString("result");
        if(result.equals("commit")){
            goodsTccService.commitStock(orderId);
        }else  if(result.equals("cancel")){
            goodsTccService.cancelStock(orderId);
        }
    }
}

订单服务

商品微服务feign

java 复制代码
public interface GoodsTccFeign {

    /**
     * 订单feign调用扣减库存时使用
     * */
    @PostMapping("/goods/stock/reduce")
    Integer tryStock(GoodsTccRequest request);//生成冻结库存记录,商品库存=商品库存-冻结库存,冻结库存状态=try
}

mq发送,用于最终一致性,要么cancel,要么commit

java 复制代码
@Slf4j
@Component
public class MessageGoodsTccSendProducer {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 异步发送消息
     * @param orderId 订单id
     * @param result 请求结果 ("commit","cancel")
     */
    public void asyncSend(String orderId,String result){
        JSONObject obj = new JSONObject();
        obj.put("orderId",orderId);
        obj.put("result",result);
        Message<String> message = MessageBuilder.withPayload(obj.toJSONString()).build();
        // 异步发送消息
        rocketMQTemplate.asyncSend("order_create", message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("消息发送Producer, message为:{}, 成功。{}", message.getPayload(), JSONObject.toJSONString(sendResult));
            }

            @Override
            public void onException(Throwable throwable) {
                log.error("消息发送Producer失败,messageId为:{}, 异常:{}", message.getPayload(), throwable.getMessage());
            }
        }, 5000, 0);
    }
}

下单controller

java 复制代码
@RestController
@RequestMapping("/order")
public class OrderCreateController {

    GoodsTccFeign goodsTccFeign;

    MessageGoodsTccSendProducer messageGoodsTccSendProducer;

    @RequestMapping("/create")
    public Map getCanGotoActivityTag(@RequestParam("skuIds") List<Integer> skuids, @RequestParam("quantitys")List<Integer> quantitys){
        GoodsTccRequest goodsTccRequest = new GoodsTccRequest();
        goodsTccRequest.setSkuIds(skuids);
        goodsTccRequest.setSkuIds(quantitys);
        String orderId = UUID.randomUUID().toString().replace("-","");
        goodsTccRequest.setOrderId(orderId);
        //冻结库存
        goodsTccFeign.tryStock(goodsTccRequest);

        //生成订单

        //如果一切正常
        String result = "commit";

        //如果异常
        //result = "cancel";

        //发送消息
        messageGoodsTccSendProducer.asyncSend(orderId,result);
        Map orderMap = new HashMap<>();
        return orderMap;
    }

}
相关推荐
吃喝不愁霸王餐APP开发者4 分钟前
Java后端服务在对接全国性霸王餐API时的多数据中心部署与就近调用策略
java·开发语言
从心归零12 分钟前
springboot-jpa的批量更新方法
java·spring boot·spring
froginwe1118 分钟前
jQuery UI 实例
开发语言
这周也會开心21 分钟前
128陷阱,==与equals区别
java·开发语言
kaikaile199528 分钟前
matlab基于人工势场法的路径规划
开发语言·matlab
沙漠豪30 分钟前
提取PDF发票信息的Python脚本
开发语言·python·pdf
youliroam44 分钟前
ESP32-S3+OV2640简单推流到GO服务
开发语言·后端·golang·esp32·ov2640
BrianGriffin1 小时前
asdf 安装的 PHP 上传文件大小限制
开发语言·php
TAEHENGV1 小时前
回收站模块 Cordova 与 OpenHarmony 混合开发实战
android·java·harmonyos
a努力。2 小时前
宇树Java面试被问:方法区、元空间的区别和演进
java·后端·面试·宇树科技