/**
* @Author: gan
* @Description:
* @File: main
* @Version: 1.0.0
* @Date: 2023/8/25 2:37 PM
*/
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"runtime"
"time"
)
var workers = runtime.NumCPU()
type result struct {
jobName string
resultCode int
resultInfo string
}
type job struct {
jobName string
results chan<- result
}
func main() {
num := 10
var jobNames []string
for i := 0; i < num; i++ {
jobNames = append(jobNames, fmt.Sprintf("%v", i))
}
exec(jobNames)
}
func exec(jobNames []string) {
jobs := make(chan job, workers)
results := make(chan result, len(jobNames))
done := make(chan struct{}, workers)
/**
* 把任务写入 JobCh通道
**/
go func(jobs chan<- job, jobNames []string, results chan<- result) {
for _, jobName := range jobNames {
jobs <- job{jobName, results}
}
close(jobs)
}(jobs, jobNames, results)
/**
* 开启n个协程处理任务
**/
for i := 0; i < workers; i++ {
go func(done chan<- struct{}, jobs <-chan job) {
for job := range jobs {
job.do()
}
done <- struct{}{}
}(done, jobs)
}
/**
* 查看任务是否完成
**/
go func(done <-chan struct{}, results chan result) {
for i := 0; i < workers; i++ {
<-done
}
close(results)
}(done, results)
/**
* 取出结果
**/
for result := range results {
fmt.Printf("done: %s,%d,%s\n", result.jobName, result.resultCode, result.resultInfo)
}
}
func (job job) do() {
// 模拟处理结果
demoRes := demoHandle()
if demoRes != "" {
job.results <- result{job.jobName, 0, "ok"}
} else {
job.results <- result{job.jobName, -1, "error"}
}
}
func demoHandle() (result string) {
url := "https://www.baidu.com"
data := map[string]interface{}{
"timestamp": 1692944539,
}
jsonData, err := json.Marshal(data)
if err != nil {
panic(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonData))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
result = string(body)
return
}
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131