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;
    }

}
相关推荐
HANDY092001 分钟前
从“不照人”到“剂量达标”:扇叶遮挡式UV-C空气消毒的工程边界与可验证评估框架
开发语言·人工智能·嵌入式硬件·智能家居
1024奇点9 小时前
【仓颉语言入门 · 第二篇 第 22 课】
开发语言·ide·开源
Warren2Lynch10 小时前
C4 模型详解:利用 Visual Paradigm 可视化软件架构的综合指南
开发语言·uml
天河归来10 小时前
第三方接口不稳定,如何让核心任务继续完成
java·大数据
Knight_AL11 小时前
Java 文件下载时文件名中的 `#` 被转换成 `%23`?一次 URL 编码与解码问题排查
java·开发语言
FRing0311 小时前
vue2干货总结2(v-bind、v-for、v-model、指令修饰符、v-bind操作class和style)
开发语言·前端·vue.js·vue2
by2099912 小时前
C++ 智能指针的所有权与使用
开发语言·c++·经验分享
砚底藏山河12 小时前
python量化自定义周期 K 线合成
java·开发语言·数据库·python·金融
IT召唤狮12 小时前
开源企业级零信任项目Pangolin,零信任能挡住PHP核弹漏洞吗?
开发语言·开源·php
知已难寻12 小时前
03 · OpenStack的计算管理 Nova
运维·服务器·开发语言·云原生·云计算·openstack·开源软件