go asynq异步任务

1.第三方库

https://github.com/hibiken/asynq

准备条件:
需要安装redis
2.client

package main

import (
	"encoding/json"
	"fmt"

	"github.com/hibiken/asynq"
)

func main() {
	client := asynq.NewClient(
		asynq.RedisClientOpt{
			Addr:     "127.0.0.1:6379",
			Password: "***", 
			DB: 0,
		})
    go startUpdate()              // 定时触发
}

//触发任务
func startUpdate() {
	updateTask()

	ticker := time.NewTicker(time.Minute*10)
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
			updateTask()
		case <-chExit.Wait():
			return
		}
	}
}

func updateTask(){
	data := map[string]string{
		"aa": "11",
		"bb": "22",
	}

	payload, _ := json.Marshal(data)

	t1 := asynq.NewTask("test99", payload)

	info, err := client.Enqueue(t1, asynq.TaskID("sdf11111"))//添加taskID,如果任务没有被消费,则入队列失败
	if err != nil {
		fmt.Printf("err:%v,info:%v\n", err, info)
	}

	fmt.Printf(" [*] Successfully enqueued task: %+v", info)
}

3.server

package main

import (
	"fmt"
	"encoding/json"

	"github.com/hibiken/asynq"
)

var AsynqServer *asynq.Server // kodo中的异步任务server

func main() {
	initTaskServer()
	mux := asynq.NewServeMux()

	mux.HandleFunc("test99", HandleUpdateTask)
	// ...register other handlers...

	if err := AsynqServer.Run(mux); err != nil {
		fmt.Printf("could not run asynq server: %v", err)
	}
}

func HandleUpdateTask(ctx context.Context, t *asynq.Task) error {
	res := make(map[string]string)

	err := json.Unmarshal(t.Payload(), &res)
	if err != nil {
		fmt.Printf("rum session, can not parse payload: %s,  err: %v", t.Payload(), err)
		return nil
	}
//--------具体处理逻辑------------//
	fmt.Printf("setting:%+#v\n", res)
	return nil
}


func initTaskServer() error {
	// 初始化异步任务服务端
	AsynqServer = asynq.NewServer(
		asynq.RedisClientOpt{
			Addr:     "127.0.0.1:6379",
			Password: "***", //与client对应
			DB:       0,
		},
		asynq.Config{
			// Specify how many concurrent workers to use
			Concurrency: 100,
			// Optionally specify multiple queues with different priority.
			Queues: map[string]int{
				"critical": 6,
				"default":  3,
				"low":      1,
			},
			// See the godoc for other configuration options
		},
	)
	return nil
}

4.UI
可以通过Asynqmon查看任务量和占用内存
go asynq异步任务_第1张图片

你可能感兴趣的:(go语言,golang,异步框架,asynq)