Go语言实现长连接并发框架 - 任务执行流
文章目录
- 前言
- 接口
- 结构体
- 接口实现
- 项目地址
- 最后
前言
你好,我是醉墨居士,上篇博客中我们实现了客户端的请求的实现,接下来我们要去实现对请求任务的处理,我们需要定义任务执行的流程
接口
trait/task.go
type TaskFunc interface {Execute(ctx Context)
}type TaskFlow interface {Extend(...TaskFunc)Append(fs ...TaskFunc) TaskFlowExecute(idx int, ctx Context)Len() intFuncs() []TaskFunc
}
结构体
gcore/task.go
// TaskFunc 任务处理函数
type TaskFunc func(trait.Context)// TaskFlow 任务处理流
type TaskFlow []trait.TaskFunc// NewTaskFlow 创建任务流
func NewTaskFlow(fs ...trait.TaskFunc) trait.TaskFlow {flow := TaskFlow(fs)return &flow
}
接口实现
gcore/task.go
// Execute 执行任务
func (h TaskFunc) Execute(ctx trait.Context) {h(ctx)
}// Extend 扩展任务处理流
func (h *TaskFlow) Extend(fs ...trait.TaskFunc) {*h = append(*h, fs...)
}// Append 追加任务处理流
func (h *TaskFlow) Append(fs ...trait.TaskFunc) trait.TaskFlow {flow := make([]trait.TaskFunc, h.Len() + len(fs))copy(flow[:h.Len()], *h)copy(flow[h.Len():], fs)return NewTaskFlow(flow...)
}// Execute 执行任务
func (h *TaskFlow) Execute(idx int, ctx trait.Context) {(*h)[idx].Execute(ctx)
}// Len 任务处理流长度
func (h *TaskFlow) Len() int {return len(*h)
}// Funcs 获取所有任务执行逻辑
func (h *TaskFlow) Funcs() []trait.TaskFunc {return *h
}
项目地址
Github:https://github.com/zm50/gte
Giee:https://gitee.com/zm50/gte
最后
我是醉墨居士,我们完成对请求的任务执行流的定义,下篇博客我们实现一下任务执行流的上下文