在现代软件开发中,任务流的管理常常让人头疼。现在,LightFlow 诞生了!这是一个基于 Go 语言的任务编排框架,旨在简化复杂任务流的设计与管理。通过函数式编程,LightFlow 使开发者能够在代码中直接定义任务流,将重点放在任务的执行时机,而无需繁琐的配置文件和规则。
通过以下命令轻松安装 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 failedstep.Get 和 step.Set 与上下文交互。查看文档init 函数中定义流程并添加步骤。查看文档flow.DoneFlow 方法开始执行流程,传入必要的输入数据。LightFlow 设计为尽可能执行所有任务,即便某个任务失败,只有依赖于该任务的后续任务会被跳过,而其他不相关的任务仍将继续运行。 这种设计支持断点恢复,确保在错误发生时系统仍能有效执行未受影响的部分。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。