图思维胜过链式思维: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仓库
相关推荐
ShowMaker.wins3 小时前
目标检测进化史
人工智能·python·神经网络·目标检测·计算机视觉·自动驾驶·视觉检测
憨憨爱编程3 小时前
机器学习-多因子线性回归
人工智能·机器学习·线性回归
大任视点3 小时前
科技赋能噪声防控,守护职业安全健康
大数据·人工智能·算法
中杯可乐多加冰3 小时前
【AI落地应用实战】利用亚马逊云科技 Step Functions 集成现有系统快速实现个性化邮件触达
大数据·人工智能·数据挖掘·数据分析·推荐系统·亚马逊云科技·step function
拉拉拉拉拉拉拉马3 小时前
DINOv3详解+实际下游任务模型使用细节(分割,深度,分类)+ Lora使用+DINOv1至v3区别变换分析(可辅助组会)
人工智能·分类·数据挖掘
anlpsonline3 小时前
AI赋能 破局重生 嬗变图强 | 安贝斯受邀参加2025第三届智能物联网与安全科技应用大会暨第七届智能化&信息化年度峰会
人工智能·物联网·安全
奶糖 肥晨3 小时前
模型驱动的 AI Agent架构:亚马逊云科技的Strands框架技术深度解析
人工智能·科技·架构
说私域3 小时前
基于定制开发开源AI智能名片S2B2C商城小程序的社群团购线上平台搭建研究
人工智能·小程序·开源
数据与人工智能律师3 小时前
从比特币到Web3:数字资产犯罪的演进史
大数据·人工智能·python·云计算·区块链