聊聊xxl-job-executor-go
序
本文主要研究一下xxl-job-executor-go
Executor
//执行器
type Executor interface {
//初始化
Init(...Option)
//日志查询
LogHandler(handler LogHandler)
//注册任务
RegTask(pattern string, task TaskFunc)
//运行任务
RunTask(writer http.ResponseWriter, request *http.Request)
//杀死任务
KillTask(writer http.ResponseWriter, request *http.Request)
//任务日志
TaskLog(writer http.ResponseWriter, request *http.Request)
//运行服务
Run() error
}
Executor定义了Init、LogHandler、RegTask、RunTask、KillTask、TaskLog、Run方法
executor
type executor struct {
opts Options
address string
regList *taskList //注册任务列表
runList *taskList //正在执行任务列表
mu sync.RWMutex
log Logger
logHandler LogHandler //日志查询handler
}
executor定义了opts、address、regList、runList、mu、log、logHandler属性
Init
func (e *executor) Init(opts ...Option) {
for _, o := range opts {
o(&e.opts)
}
e.log = e.opts.l
e.regList = &taskList{
data: make(map[string]*Task),
}
e.runList = &taskList{
data: make(map[string]*Task),
}
e.address = e.opts.ExecutorIp + ":" + e.opts.ExecutorPort
go e.registry()
}
Init方法遍历opts应用opt,然后初始化regList、runList、address,最后异步e.registry()
RegTask
//注册任务
func (e *executor) RegTask(pattern string, task TaskFunc) {
var t = &Task{}
t.fn = task
e.regList.Set(pattern, t)
return
}
RegTask方法往regList添加指定pattern的task
runTask
func (e *executor) runTask(writer http.ResponseWriter, request *http.Request) {
e.mu.Lock()
defer e.mu.Unlock()
req, _ := ioutil.ReadAll(request.Body)
param := &RunReq{}
err := json.Unmarshal(req, ¶m)
if err != nil {
_, _ = writer.Write(returnCall(param, 500, "params err"))
e.log.Error("参数解析错误:" + string(req))
return
}
e.log.Info("任务参数:%v", param)
if !e.regList.Exists(param.ExecutorHandler) {
_, _ = writer.Write(returnCall(param, 500, "Task not registered"))
e.log.Error("任务[" + Int64ToStr(param.JobID) + "]没有注册:" + param.ExecutorHandler)
return
}
//阻塞策略处理
if e.runList.Exists(Int64ToStr(param.JobID)) {
if param.ExecutorBlockStrategy == coverEarly { //覆盖之前调度
oldTask := e.runList.Get(Int64ToStr(param.JobID))
if oldTask != nil {
oldTask.Cancel()
e.runList.Del(Int64ToStr(oldTask.Id))
}
} else { //单机串行,丢弃后续调度 都进行阻塞
_, _ = writer.Write(returnCall(param, 500, "There are tasks running"))
e.log.Error("任务[" + Int64ToStr(param.JobID) + "]已经在运行了:" + param.ExecutorHandler)
return
}
}
cxt := context.Background()
task := e.regList.Get(param.ExecutorHandler)
if param.ExecutorTimeout > 0 {
task.Ext, task.Cancel = context.WithTimeout(cxt, time.Duration(param.ExecutorTimeout)*time.Second)
} else {
task.Ext, task.Cancel = context.WithCancel(cxt)
}
task.Id = param.JobID
task.Name = param.ExecutorHandler
task.Param = param
task.log = e.log
e.runList.Set(Int64ToStr(task.Id), task)
go task.Run(func(code int64, msg string) {
e.callback(task, code, msg)
})
e.log.Info("任务[" + Int64ToStr(param.JobID) + "]开始执行:" + param.ExecutorHandler)
_, _ = writer.Write(returnGeneral())
}
runTask方法先判断task是否已经注册了,则根据ExecutorBlockStrategy做不同处理,若是coverEarly则cancel掉已有的task;最后通过task.Run来异步执行任务
killTask
func (e *executor) killTask(writer http.ResponseWriter, request *http.Request) {
e.mu.Lock()
defer e.mu.Unlock()
req, _ := ioutil.ReadAll(request.Body)
param := &killReq{}
_ = json.Unmarshal(req, ¶m)
if !e.runList.Exists(Int64ToStr(param.JobID)) {
_, _ = writer.Write(returnKill(param, 500))
e.log.Error("任务[" + Int64ToStr(param.JobID) + "]没有运行")
return
}
task := e.runList.Get(Int64ToStr(param.JobID))
task.Cancel()
e.runList.Del(Int64ToStr(param.JobID))
_, _ = writer.Write(returnGeneral())
}
killTask方法则执行task.Cancel(),同时将其从runList移除
taskLog
func (e *executor) taskLog(writer http.ResponseWriter, request *http.Request) {
var res *LogRes
data, err := ioutil.ReadAll(request.Body)
req := &LogReq{}
if err != nil {
e.log.Error("日志请求失败:" + err.Error())
reqErrLogHandler(writer, req, err)
return
}
err = json.Unmarshal(data, &req)
if err != nil {
e.log.Error("日志请求解析失败:" + err.Error())
reqErrLogHandler(writer, req, err)
return
}
e.log.Info("日志请求参数:%+v", req)
if e.logHandler != nil {
res = e.logHandler(req)
} else {
res = defaultLogHandler(req)
}
str, _ := json.Marshal(res)
_, _ = writer.Write(str)
}
taskLog方法通过e.logHandler(req)或者defaultLogHandler(req)来获取日志
小结
xxl-job-executor-go的Executor定义了Init、LogHandler、RegTask、RunTask、KillTask、TaskLog、Run方法;executor实现了Executor接口,并提供了http的api接口。
doc
code-craft
spring boot , docker and so on 欢迎关注微信公众号: geek_luandun
推荐阅读
2022年终总结
最近两年开始陷入颓废中,博客也写的越来越少了。究其原因,主要还是陷入了职业倦怠期,最近一次跳槽感觉颇为失败,但是碍于给的薪资高,为了五斗米折腰,又加上最近行情不好,想要往外跳也跳不了,就这样子一直...
codecraft阅读 715
Golang 中 []byte 与 string 转换
string 类型和 []byte 类型是我们编程时最常使用到的数据结构。本文将探讨两者之间的转换方式,通过分析它们之间的内在联系来拨开迷雾。
机器铃砍菜刀赞 22阅读 55.1k评论 1
年度最佳【golang】map详解
这篇文章主要讲 map 的赋值、删除、查询、扩容的具体执行过程,仍然是从底层的角度展开。结合源码,看完本文一定会彻底明白 map 底层原理。
去去1002赞 14阅读 11k评论 2
年度最佳【golang】GMP调度详解
Golang最大的特色可以说是协程(goroutine)了, 协程让本来很复杂的异步编程变得简单, 让程序员不再需要面对回调地狱, 虽然现在引入了协程的语言越来越多, 但go中的协程仍然是实现的是最彻底的. 这篇文章将通过分析...
去去1002赞 13阅读 11.2k评论 4
【已结束】SegmentFault 思否技术征文丨浅谈 Go 语言框架
亲爱的开发者们:我们的 11 月技术征文如期而来,这次主题围绕 「 Go 」 语言,欢迎大家来参与分享~征文时间11 月 4 日 - 11 月 27 日 23:5911 月 28 日 18:00 前发布中奖名单参与条件新老思否作者均可参加征文...
SegmentFault思否赞 11阅读 4.7k评论 11
【Go微服务】开发gRPC总共分三步
之前我也有写过RPC相关的文章:《 Go RPC入门指南:RPC的使用边界在哪里?如何实现跨语言调用?》,详细介绍了RPC是什么,使用边界在哪里?并且用Go和php举例,实现了跨语言调用。不了解RPC的同学建议先读这篇文...
王中阳Go赞 8阅读 3.7k评论 6
【golang】sync.WaitGroup详解
上一期中,我们介绍了 sync.Once 如何保障 exactly once 语义,本期文章我们介绍 package sync 下的另一个工具类:sync.WaitGroup。
去去1002赞 13阅读 30.2k评论 2
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。