责任链模式+CompletableFuture异步处理

1、查询商品基础信息
2、查询商品价格
3、查询商品活动
4、查询商品库存

假设这几个服务逻辑比较独立,其实是可以并行调用,我们可以结合责任链模式和CompletableFuture进行优化:

下面是代码示例:

java 复制代码
@Service
public class ChainFactory {
    // 原型模式获取对象

    @Resource
    private  Map<String, ILogicChain> strategyChainGroup;

    public ChainFactory(Map<String, ILogicChain> strategyChainGroup) {
        this.strategyChainGroup = strategyChainGroup;
    }

    /**
     * 构建责任链并获取所有处理器的 CompletableFuture 数组
     *
     * @param productInfo 商品信息对象
     * @return CompletableFuture 数组
     */
    public CompletableFuture<Void>[] openLogicChain(ProductInfo productInfo) {
        // 按照配置顺序装填责任链;
        ILogicChain logicChain = strategyChainGroup.get(LogicModel.BASIC_INFO_SERVICE_HANDLER.getCode());
        ILogicChain current = logicChain;
        List<CompletableFuture<Void>> futures = new ArrayList<>();

        //遍历LogicModel的code
        LogicModel[] ruleModels = LogicModel.values();
        for (int i = 1; i < ruleModels.length; i++) {
            ILogicChain nextChain = strategyChainGroup.get(ruleModels[i].getCode());
            current.appendNext(nextChain);
        }

        // 获取所有处理器的 CompletableFuture
        current = logicChain;
        while (current != null) {
            CompletableFuture<Void> future = current.logic(productInfo);
            futures.add(future);
            current = current.next();
        }

        return futures.toArray(new CompletableFuture[0]);
    }


    @Getter
    @AllArgsConstructor
    public enum LogicModel {

        BASIC_INFO_SERVICE_HANDLER("basicInfoServiceHandler", "实现商品基础信息补全节点"),
        PRICE_SERVICE_HANDLER("priceServiceHandler", "实现商品价格补全节点"),
        ACTIVITY_SERVICE_HANDLER("activityServiceHandler", "实现商品活动补全节点"),
        INVENTORY_SERVICE_HANDLER("inventoryServiceHandler", "实现商品库存服务节点")
        ;

        private final String code;
        private final String info;

    }

}
java 复制代码
@Slf4j
@Component("activityServiceHandler")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class ActivityServiceHandler extends AbstractLogicChain {
    @Override
    public CompletableFuture<Void> logic(ProductInfo productInfo) {
        CompletableFuture<Void> future = new CompletableFuture<>();
        // 模拟异步调用外部服务,修改商品信息对象
        CompletableFuture.runAsync(() -> {
            // 补充商品活动数据
            productInfo.setActivity("...");
            //休眠10秒
            try {
                TimeUnit.SECONDS.sleep(10);
                log.info("activityServiceHandler logic 结束:{}",now());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            future.complete(null);
        });
        return future;
    }

}
java 复制代码
@Slf4j
@Component("basicInfoServiceHandler")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class BasicInfoServiceHandler extends AbstractLogicChain {


    @Override
    public CompletableFuture<Void> logic(ProductInfo productInfo) {
        CompletableFuture<Void> future = new CompletableFuture<>();
        // 模拟异步调用外部服务,修改商品信息对象
        CompletableFuture.runAsync(() -> {
            // 补充商品基础信息数据
            productInfo.setBasicInfo("...");
            //休眠10秒
            try {
                TimeUnit.SECONDS.sleep(10);
                log.info("basicInfoServiceHandler logic 结束:{}",now());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            future.complete(null);
        });
        return future;
    }

}
java 复制代码
@Slf4j
@Component("inventoryServiceHandler")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class InventoryServiceHandler extends AbstractLogicChain {


    @Override
    public CompletableFuture<Void> logic(ProductInfo productInfo) {
        CompletableFuture<Void> future = new CompletableFuture<>();
        // 模拟异步调用外部服务,修改商品信息对象
        CompletableFuture.runAsync(() -> {
            // 补充商品库存数据
            productInfo.setInventory(100);
            //休眠10秒
            try {
                TimeUnit.SECONDS.sleep(10);
                log.info("inventoryServiceHandler logic 结束:{}",now());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            future.complete(null);
        });
        return future;
    }
}
java 复制代码
@Slf4j
@Component("priceServiceHandler")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class PriceServiceHandler extends AbstractLogicChain {


    @Override
    public CompletableFuture<Void> logic(ProductInfo productInfo) {
        CompletableFuture<Void> future = new CompletableFuture<>();
        // 模拟异步调用外部服务,修改商品信息对象
        CompletableFuture.runAsync(() -> {
            // 补充商品价格数据
            productInfo.setPrice(100.0);
            //休眠10秒
            try {
                TimeUnit.SECONDS.sleep(10);
                log.info("priceServiceHandler logic 结束:{}",now());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            future.complete(null);
        });
        return future;
    }


}
java 复制代码
@Data
public class ProductInfo {
    //模拟商品基础信息
    private String basicInfo;
    //商品价格
    private double price;
    //模拟商品活动信息
    private String activity;
    //模拟商品库存
    private int inventory;

    // 省略构造函数、getter和setter
}
java 复制代码
@Slf4j
public abstract class AbstractLogicChain implements ILogicChain {

    private ILogicChain next;

    @Override
    public ILogicChain next() {
        return next;
    }

    @Override
    public ILogicChain appendNext(ILogicChain next) {
        this.next = next;
        return next;
    }


}
java 复制代码
public interface ILogicChain extends ILogicChainArmory, Cloneable {

    /**
     * 责任链接口
     *
     * @param productInfo    请求对象
     * @return
     */
    CompletableFuture<Void> logic(ProductInfo productInfo);

}
java 复制代码
public interface ILogicChainArmory {

    ILogicChain next();

    ILogicChain appendNext(ILogicChain next);

}

测试类

java 复制代码
@Resource
    private ChainFactory chainFactory;


    @Test
    public void testAsyncChain() {
        // 创建一个 ProductInfo 对象
        ProductInfo productInfo = new ProductInfo();

		// 获取所有处理器的 CompletableFuture 数组
        CompletableFuture<Void>[] futures = chainFactory.openLogicChain(productInfo);

        // 等待所有责任链处理完成
        CompletableFuture.allOf(futures).join();

        log.info("结束");
    }
相关推荐
想要成为计算机高手3 分钟前
4. isaac sim4.2 教程-Core API-Hello robot
人工智能·python·机器人·英伟达·isaac sim·仿真环境
teeeeeeemo16 分钟前
http和https的区别
开发语言·网络·笔记·网络协议·http·https
wuxuanok22 分钟前
Web后端开发-Mybatis
java·开发语言·笔记·学习·mybatis
陈敬雷-充电了么-CEO兼CTO1 小时前
复杂任务攻坚:多模态大模型推理技术从 CoT 数据到 RL 优化的突破之路
人工智能·python·神经网络·自然语言处理·chatgpt·aigc·智能体
卷到起飞的数分1 小时前
Java零基础笔记07(Java编程核心:面向对象编程 {类,static关键字})
java·开发语言·笔记
YOLO大师1 小时前
华为OD机试 2025B卷 - 小明减肥(C++&Python&JAVA&JS&C语言)
c++·python·华为od·华为od机试·华为od2025b卷·华为机试2025b卷·华为od机试2025b卷
谁他个天昏地暗1 小时前
Java 实现 Excel 文件对比与数据填充
java·开发语言·excel
xiao5kou4chang6kai41 小时前
【Python-GEE】如何利用Landsat时间序列影像通过调和回归方法提取农作物特征并进行分类
python·gee·森林监测·洪涝灾害·干旱评估·植被变化
kaikaile19951 小时前
使用Python进行数据可视化的初学者指南
开发语言·python·信息可视化
大P哥阿豪1 小时前
Go defer(二):从汇编的角度理解延迟调用的实现
开发语言·汇编·后端·golang