图思维胜过链式思维:JGraphlet构建任务流水线的八大核心原则

图思维胜过链式思维:JGraphlet构建任务流水线 🚀

JGraphlet是一个轻量级、零依赖的Java库,用于构建任务流水线。它的强大之处不在于冗长的功能列表,而在于一小套协同工作的核心设计原则。

JGraphlet的核心是简洁性,基于图模型构建。向流水线添加任务并连接它们以创建图。 每个任务都有输入和输出,TaskPipeline构建并执行流水线,同时管理每个任务的I/O。例如,使用Map进行扇入操作,使用Record定义自定义数据模型等。TaskPipeline还包含PipelineContext在任务间共享数据,此外任务还可以被缓存,避免重复计算。

您可以自定义任务流水线的流程,并选择使用SyncTask或AsyncTask。默认情况下所有任务都是异步的。

1. 图优先执行模型

JGraphlet将工作流视为有向无环图。您将任务定义为节点,并显式绘制它们之间的连接。这使得扇出和扇入等复杂模式变得自然。

java 复制代码
import dev.shaaf.jgraphlet.*;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

try (TaskPipeline pipeline = new TaskPipeline()) {
    Task<String, String> fetchInfo = (id, ctx) -> CompletableFuture.supplyAsync(() -> "Info for " + id);
    Task<String, String> fetchFeed = (id, ctx) -> CompletableFuture.supplyAsync(() -> "Feed for " + id);
    Task<Map<String, Object>, String> combine = (inputs, ctx) -> CompletableFuture.supplyAsync(() ->
        inputs.get("infoNode") + " | " + inputs.get("feedNode")
    );

    pipeline.addTask("infoNode", fetchInfo)
            .addTask("feedNode", fetchFeed)
            .addTask("summaryNode", combine);

    pipeline.connect("infoNode", "summaryNode")
            .connect("feedNode", "summaryNode");

    String result = (String) pipeline.run("user123").join();
    System.out.println(result); // "Info for user123 | Feed for user123"
}

2. 两种任务风格:Task<I,O>和SyncTask<I,O>

JGraphlet提供两种可混合使用的任务类型:

  • Task<I, O>(异步):返回CompletableFuture,适合I/O操作或繁重计算
  • SyncTask<I, O>(同步):直接返回O,适合快速的CPU密集型操作
java 复制代码
try (TaskPipeline pipeline = new TaskPipeline()) {
    Task<String, String> fetchName = (userId, ctx) ->
        CompletableFuture.supplyAsync(() -> "John Doe");

    SyncTask<String, String> toUpper = (name, ctx) -> name.toUpperCase();

    pipeline.add("fetch", fetchName)
            .then("transform", toUpper);

    String result = (String) pipeline.run("user-42").join();
    System.out.println(result); // "JOHN DOE"
}

3. 简单显式的API

JGraphlet避免复杂的构建器或魔法配置,API简洁明了:

  • 创建流水线:new TaskPipeline()
  • 注册节点:addTask("uniqueId", task)
  • 连接节点:connect("fromId", "toId")
java 复制代码
try (TaskPipeline pipeline = new TaskPipeline()) {
    SyncTask<String, Integer> lengthTask = (s, c) -> s.length();
    SyncTask<Integer, String> formatTask = (i, c) -> "Length is " + i;

    pipeline.addTask("calculateLength", lengthTask);
    pipeline.addTask("formatOutput", formatTask);

    pipeline.connect("calculateLength", "formatOutput");

    String result = (String) pipeline.run("Hello").join();
    System.out.println(result); // "Length is 5"
}

4. 清晰的扇入输入形状

扇入任务接收Map<String, Object>,其中键是父任务ID,值是它们的结果。

java 复制代码
try (TaskPipeline pipeline = new TaskPipeline()) {
    SyncTask<String, String> fetchUser = (id, ctx) -> "User: " + id;
    SyncTask<String, String> fetchPerms = (id, ctx) -> "Role: admin";

    Task<Map<String, Object>, String> combine = (inputs, ctx) -> CompletableFuture.supplyAsync(() -> {
        String userData = (String) inputs.get("userNode");
        String permsData = (String) inputs.get("permsNode");
        return userData + " (" + permsData + ")";
    });

    pipeline.addTask("userNode", fetchUser)
            .addTask("permsNode", fetchPerms)
            .addTask("combiner", combine);

    pipeline.connect("userNode", "combiner").connect("permsNode", "combiner");

    String result = (String) pipeline.run("user-1").join();
    System.out.println(result); // "User: user-1 (Role: admin)"
}

5. 清晰的运行契约

执行流水线很简单:pipeline.run(input)返回最终结果的CompletableFuture。您可以使用.join()阻塞或使用异步链式调用。

java 复制代码
String input = "my-data";

// 阻塞方式
try {
    String result = (String) pipeline.run(input).join();
    System.out.println("Result (blocking): " + result);
} catch (Exception e) {
    System.err.println("Pipeline failed: " + e.getMessage());
}

// 非阻塞方式
pipeline.run(input)
        .thenAccept(result -> System.out.println("Result (non-blocking): " + result))
        .exceptionally(ex -> {
            System.err.println("Async pipeline failed: " + ex.getMessage());
            return null;
        });

6. 内置资源生命周期

JGraphlet实现AutoCloseable。使用try-with-resources保证内部资源的安全关闭。

java 复制代码
try (TaskPipeline pipeline = new TaskPipeline()) {
    pipeline.add("taskA", new SyncTask<String, String>() {
        @Override
        public String executeSync(String input, PipelineContext context) {
            if (input == null) {
                throw new IllegalArgumentException("Input cannot be null");
            }
            return "Processed: " + input;
        }
    });

    pipeline.run("data").join();

} // pipeline.shutdown()自动调用
System.out.println("Pipeline resources have been released.");

7. 上下文

PipelineContext是线程安全的、每次运行的工作空间,用于存储元数据。

java 复制代码
SyncTask<String, String> taskA = (input, ctx) -> {
    ctx.put("requestID", "xyz-123");
    return input;
};
SyncTask<String, String> taskB = (input, ctx) -> {
    String reqId = ctx.get("requestID", String.class).orElse("unknown");
    return "Processed input " + input + " for request: " + reqId;
};

8. 可选缓存

任务可以选择加入缓存以避免重复计算。

java 复制代码
Task<String, String> expensiveApiCall = new Task<>() {
    @Override
    public CompletableFuture<String> execute(String input, PipelineContext context) {
        System.out.println("Performing expensive call for: " + input);
        return CompletableFuture.completedFuture("Data for " + input);
    }
    @Override
    public boolean isCacheable() { return true; }
};

try (TaskPipeline pipeline = new TaskPipeline()) {
    pipeline.add("expensive", expensiveApiCall);

    System.out.println("First call...");
    pipeline.run("same-key").join();

    System.out.println("Second call...");
    pipeline.run("same-key").join(); // 结果来自缓存
}

最终结果是提供了一种清晰、可测试的方式来编排同步或异步任务,用于组合复杂流程,如并行检索、合并、判断和防护栏,而无需引入重量级的工作流引擎。

了解更多或尝试使用:

  • Maven中央仓库
  • Github仓库
相关推荐
小明_GLC15 分钟前
Falcon-TST: A Large-Scale Time Series Foundation Model
论文阅读·人工智能·深度学习·transformer
Python_Study202515 分钟前
制造业数据采集系统选型指南:从技术挑战到架构实践
大数据·网络·数据结构·人工智能·架构
一只大侠的侠19 分钟前
【工业AI热榜】LSTM+GRU融合实战:设备故障预测准确率99.3%,附开源数据集与完整代码
人工智能·gru·lstm
weisian15126 分钟前
入门篇--知名企业-26-华为-2--华为VS阿里:两种科技路径的较量与共生
人工智能·科技·华为·阿里
棒棒的皮皮33 分钟前
【深度学习】YOLO模型精度优化 Checklist
人工智能·深度学习·yolo·计算机视觉
线束线缆组件品替网40 分钟前
Bulgin 防水圆形线缆在严苛环境中的工程实践
人工智能·数码相机·自动化·软件工程·智能电视
Cherry的跨界思维1 小时前
【AI测试全栈:Vue核心】22、从零到一:Vue3+ECharts构建企业级AI测试可视化仪表盘项目实战
vue.js·人工智能·echarts·vue3·ai全栈·测试全栈·ai测试全栈
冬奇Lab1 小时前
【Cursor进阶实战·07】OpenSpec实战:告别“凭感觉“,用规格驱动AI编程
人工智能·ai编程
玖疯子1 小时前
2025年总结框架
人工智能
dazzle1 小时前
计算机视觉处理(OpenCV基础教学(十九):图像轮廓特征查找技术详解)
人工智能·opencv·计算机视觉