美文网首页
2. springCloud Stream 实现异步扣库存

2. springCloud Stream 实现异步扣库存

作者: 呆叔么么 | 来源:发表于2020-05-27 21:30 被阅读0次

一.原扣库存逻辑

...
        // 6.扣库存
        List<DecreaseStockInput> decreaseStockInputList = orderDTO.getOrderItemList().stream().map(e -> {
            DecreaseStockInput decreaseStockInput = new DecreaseStockInput();
            decreaseStockInput.setGoodsId(e.getGoodsId());
            decreaseStockInput.setGoodsStock(e.getGoodsCount());
            return decreaseStockInput;
        }).collect(Collectors.toList());
        /**
        * 使用Feign调用微服务
        */

        count = productClient.decreaseStock(decreaseStockInputList);
        if(count < 0){
            throw new OrderException(ExceptionCodeEnum.ORDER_SAVE_FAIL);
        }
...

二.使用SpringCloud Stream 异步下单

order服务

...
        // 6.扣库存
        List<DecreaseStockInput> decreaseStockInputList = orderDTO.getOrderItemList().stream().map(e -> {
            DecreaseStockInput decreaseStockInput = new DecreaseStockInput();
            decreaseStockInput.setGoodsId(e.getGoodsId());
            decreaseStockInput.setGoodsStock(e.getGoodsCount());
            return decreaseStockInput;
        }).collect(Collectors.toList());

        String json = GsonUtil.toJson(decreaseStockInputList);
        sender.sendMessage(json);
...

product服务

@EnableBinding(Barista.class)
@Service
@Slf4j
public class RabbitmqReceiver {

    @Autowired
    private GoodsInfoService goodsInfoService;

    @StreamListener(Barista.INPUT_CHANNEL)
    @SendTo(Barista.OUTPUT_SENDTO_CHANNEL)
    public String receiver(String message){
        log.info("【product】message=>{}",message);
        String delMsg = String.format("【product】message=>%s",message);
        /**
         * 业务逻辑处理 减库存
         */
        List<DecreaseStockInput> decreaseStockInputList = (List<DecreaseStockInput>)GsonUtil.fromJson(message, new TypeToken<List<DecreaseStockInput>>(){}.getType());
        goodsInfoService.decreaseStock(decreaseStockInputList);
        return delMsg;
    }

    @StreamListener(Barista.INPUT_SENDTO_CHANNEL)
    public void sendToReceiver(String message){
        log.info("处理之后的信息=>{}",message);
    }
}

即可实现的简易的异步扣库存

相关文章

网友评论

      本文标题:2. springCloud Stream 实现异步扣库存

      本文链接:https://www.haomeiwen.com/subject/foccgctx.html