GolangNote

Golang笔记

otium/queue 是go 实现的后台处理任务队列

Permalink

otium/queue 是 go 实现的后台处理任务队列,轻巧,值得推荐。

go queue

一个简单的应用场合,用户上传一个头像,要生成8种不同尺寸的缩略图,假设每处理一个缩略图要1秒,如果是单队列则处理完要8秒,如果同时有8个协程处理,则只需要1秒。

下面是简单的otium/queue 示例:

Go: queue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package main

import (
  "fmt"
  "time"

  "github.com/otium/queue"
)

func main() {
  n := 1  // 并发处理数
  t1 := time.Now()
  fmt.Println("Hello, 世界")

  q := queue.NewQueue(func(val interface{}) {
    fmt.Println(val)
    time.Sleep(time.Second * 2)
  }, n)
  for i := 0; i < 20; i++ {
    q.Push(i)
  }
  fmt.Println("Hello, 世界 2")
  q.Wait()
  fmt.Println("Hello, 世界3")
  t2 := time.Now()
  fmt.Println("消耗时间:", t2.Sub(t1), "秒")
}

输出:

Bash: 输出
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Hello, 世界
0
Hello, 世界 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Hello, 世界3
消耗时间: 40.00296549s 秒

把并发处理数 n 改为20 ,输出:

Bash: 输出
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Hello, 世界
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Hello, 世界 2
18
19
Hello, 世界3
消耗时间: 2.000654742s 秒

但这样的并发任务没有传递任务的计算结果,如果需要获得计算结果,就得借助 chan 来完成。

otium/queue 项目地址 https://github.com/otium/queue

另外一个简单的后台任务实现 https://gist.github.com/harlow/dbcd639cf8d396a2ab73 (用标准库) 《Writing worker queues, in Go

另外推荐一个比较复杂的 RichardKnop/machinery 基于分布式消息传递的异步任务队列/作业队列。

本文网址: https://golangnote.com/topic/53.html 转摘请注明来源

Related articles

Write a Comment to "otium/queue 是go 实现的后台处理任务队列"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 1ms