lightflow一个基于函数式编程的任务编排框架 | go作品分享 -金年会app官方网

在现代软件开发中,任务流的管理常常让人头疼。现在, 诞生了!这是一个基于 go 语言的任务编排框架,旨在简化复杂任务流的设计与管理。通过函数式编程,lightflow 使开发者能够在代码中直接定义任务流,将重点放在任务的执行时机,而无需繁琐的配置文件和规则。

为什么选择 lightflow?

  1. 简化任务流管理:告别外部规则语言,lightflow 允许开发者在代码中定义所有任务依赖,减少频繁切换上下文的烦恼。

  2. 专注执行时机:只需明确任务的依赖步骤,框架将自动处理任务执行顺序,极大降低全局依赖管理的复杂性。

  3. 提升维护性和可扩展性:即使任务流不断扩展,确定任务执行时机仍然是一项简单而基本的工作。

核心特性

  • :各个步骤通过独立的上下文链接,确保只访问相关数据,避免全局混乱。

  • :灵活地定义任务流,精准控制任务的执行时机,实现高效管理。

  • :允许将现有流程合并到新的流程中,优化整体管理。

  • :自动处理资源的分配和释放,支持断点恢复。

  • :支持任务在失败后从失败点恢复执行,避免重复运行。

  • :根据条件灵活决定任务的执行与跳过。

  • :在多个层级设置回调,轻松管理任务状态。

  • :处理任务执行阶段外的错误,允许为每个阶段配置事件处理器。

  • :用户可以根据需求自定义持久化插件,lightflow 不与任何 orm 框架耦合,灵活性更高。

快速上手

安装

通过以下命令轻松安装 lightflow:

go get github.com/bilibotter/light-flow/flow

示例代码

以下示例展示了如何使用 lightflow 进行任务编排:

package main
import (
    "fmt"
    "github.com/bilibotter/light-flow/flow"
)
func first(step flow.step) (any, error) {
    if input, exist := step.get("input"); exist {
        fmt.printf("[step: %s] get input: %v\n", step.name(), input)
    }
    step.set("key", "value")
    return "result", nil
}
func second(step flow.step) (any, error) {
    if value, exist := step.get("key"); exist {
        fmt.printf("[step: %s] get key: %v\n", step.name(), value)
    }
    if result, exist := step.result(step.dependents()[0]); exist {
        fmt.printf("[step: %s] get result: %v\n", step.name(), result)
    }
    return nil, nil
}
func errorstep(step flow.step) (any, error) {
    if value, exist := step.get("key"); exist {
        fmt.printf("[step: %s] get key: %v\n", step.name(), value)
    } else {
        fmt.printf("[step: %s] cannot get key \n", step.name())
    }
    return nil, fmt.errorf("execute failed")
}
func errorhandler(step flow.step) (bool, error) {
    if step.has(flow.failed) {
        fmt.printf("[step: %s] has failed\n", step.name())
    } else {
        fmt.printf("[step: %s] success\n", step.name())
    }
    return true, nil
}
func init() {
    process := flow.flowwithprocess("example")
    process.follow(first, second)
    process.follow(errorstep)
    process.afterstep(true, errorhandler)
}
func main() {
    flow.doneflow("example", map[string]any{"input": "hello world"})
}

输出示例

执行上述代码后,你将看到如下输出:

[step: first] get input: hello world
[step: first] success
[step: second] get key: value
[step: second] get result: result
[step: second] success
[step: errorstep] cannot get key 
[step: errorstep] has failed

使用步骤

  1. 定义步骤:编写你的 step 函数,使用 step.getstep.set 与上下文交互。

  2. 创建流程:在 init 函数中定义流程并添加步骤。

  3. 错误处理:利用回调管理各种错误情况。

  4. 启动执行:调用 flow.doneflow 方法开始执行流程,传入必要的输入数据。

lightflow 设计为尽可能执行所有任务,即便某个任务失败,只有依赖于该任务的后续任务会被跳过,而其他不相关的任务仍将继续运行。

这种设计支持断点恢复,确保在错误发生时系统仍能有效执行未受影响的部分。

讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
网站地图