iris和xxl-job整合
在以前的文章中go任务调器gocron和xxl-job 尝试xxl和gin的整合,由于项目统一用iris 所以需要研究出如何与iris整合, 直接上代码:
package main import ( "context" "fmt" "log" "github.com/kataras/iris/v12" "github.com/xxl-job/xxl-job-executor-go" ) func main() { exec := xxl.NewExecutor( xxl.ServerAddr("http://192.168.100.30:9080/xxl-job-admin"), xxl.AccessToken(""), //请求令牌(默认为空) xxl.ExecutorIp("192.168.100.2"), //可自动获取 xxl.ExecutorPort("9999"), //默认9999(非必填) xxl.RegistryKey("golang-jobs"), //执行器名称 xxl.SetLogger(&logger{}), //自定义日志 ) exec.Init() //设置日志查看handler exec.LogHandler(func(req *xxl.LogReq) *xxl.LogRes { return &xxl.LogRes{Code: 200, Msg: "", Content: xxl.LogResContent{ FromLineNum: req.FromLineNum, ToLineNum: 2, LogContent: "这个是自定义日志handler", IsEnd: true, }} }) //添加到iris路由 app := iris.New() app.Post("run", func(ctx iris.Context) { exec.RunTask(ctx.ResponseWriter(), ctx.Request()) }) app.Post("kill", func(ctx iris.Context) { exec.KillTask(ctx.ResponseWriter(), ctx.Request()) }) app.Post("log", func(ctx iris.Context) { exec.TaskLog(ctx.ResponseWriter(), ctx.Request()) }) //注册iris的handler app.Get("/", func(ctx iris.Context) { ctx.WriteString("pong") }) //注册任务handler exec.RegTask("golang.test", Task_Test) log.Fatal(app.Run(iris.Addr(":9999"))) } //xxl.Logger接口实现 type logger struct{} func (l *logger) Info(format string, a ...interface{}) { fmt.Println(fmt.Sprintf("自定义日志 - "+format, a...)) } func (l *logger) Error(format string, a ...interface{}) { log.Println(fmt.Sprintf("自定义日志 - "+format, a...)) } func Task_Test(cxt context.Context, param *xxl.RunReq) (msg string) { fmt.Println("test one task " + param.ExecutorHandler + " param:" + param.ExecutorParams + " log_id:" + xxl.Int64ToStr(param.LogID)) fmt.Println(cxt) return "iris test done" }
本地运行结果:
k8s运行:
Dockerfile
FROM golang:1.15.6 RUN mkdir -p /app WORKDIR /app ADD main /app/main EXPOSE 30903 CMD ["./main"]
build.sh
#!/bin/bash #cd $WORKSPACE export GOPROXY=https://goproxy.io #根据 go.mod 文件来处理依赖关系。 go mod tidy # linux环境编译 CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o main # 构建docker镜像,项目中需要在当前目录下有dockerfile,否则构建失败 docker build -t xlliris . docker tag xlliris 192.168.100.30:8080/go/xlliris:2021 docker login -u admin -p '123456' 192.168.100.30:8080 docker push 192.168.100.30:8080/go/xlliris docker rmi xlliris docker rmi 192.168.100.30:8080/go/xlliris:2021
deploy.yaml
apiVersion: apps/v1 kind: Deployment metadata: name: xlliris namespace: go labels: app: xlliris version: v1 spec: replicas: 1 minReadySeconds: 10 selector: matchLabels: app: xlliris version: v1 template: metadata: labels: app: xlliris version: v1 spec: imagePullSecrets: - name: regsecret containers: - name: xlliris image: 192.168.100.30:8080/go/xlliris:2021 ports: - containerPort: 30903 imagePullPolicy: Always --- apiVersion: v1 kind: Service metadata: name: xlliris namespace: go labels: app: xlliris version: v1 spec: type: NodePort ports: - port: 30903 targetPort: 30903 nodePort: 30903 protocol: TCP selector: app: xlliris
运行结果:
windows技术爱好者