-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexample.go
More file actions
107 lines (87 loc) · 2.08 KB
/
example.go
File metadata and controls
107 lines (87 loc) · 2.08 KB
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
package grpool
import (
"fmt"
"time"
"math/rand"
)
// example 1 打印日志的 async 任务
var random = rand.New(rand.NewSource(time.Now().Unix()))
var LogPool = NewPool(1000, 5)
func SendLog(msg string) error {
time.Sleep(time.Duration(random.Intn(20)+20) * time.Duration(time.Millisecond))
return nil
}
func SendLogs(msgs []string) {
executor := NewAsyncExecutor(LogPool)
for i, msg := range msgs {
index := i
message := msg
executor.AddTask(func() {
SendLog(message)
fmt.Printf("[Task %v] send log finish. msg: %v\n", index, message)
})
}
}
func TestSendLog() {
var msgs []string
msgNum := 20
for i := 0; i < msgNum; i++ {
msgs = append(msgs, fmt.Sprintf("i am msg %v", i))
}
SendLogs(msgs)
}
// example 2 查询 mysql Future 任务
var MysqlPool = NewPool(1000, 5)
type User struct {
ID int
Name string
}
func SelectUser(id int) (*User, error) {
cost := random.Intn(100)
time.Sleep(time.Duration(cost) * time.Duration(time.Millisecond))
if cost < 2 {
panic("connection refused")
}
if cost > 98 {
return nil, fmt.Errorf("time out: %vms", cost)
}
return &User{
ID: id,
Name: fmt.Sprintf("I AM %v", id),
}, nil
}
func BatchSelectUser(ids []int) map[int]*User {
executor := NewFutureExecutor(MysqlPool)
for _, id := range ids {
lId := id
executor.AddTask(func() (interface{}, error) {
return SelectUser(lId)
})
}
resultList, errorList := executor.WaitWithTimeout(1000 * time.Duration(time.Millisecond))
userMap := make(map[int]*User, 0)
for i, id := range ids {
if errorList[i] != nil {
fmt.Printf("[ERROR] select user error. id: %v, err: %v\n", id, errorList[i])
} else {
user, ok := resultList[i].(*User)
if !ok { // impossible
fmt.Printf("[ERROR] unknown result. id: %v\n", id)
} else {
fmt.Printf("[INFO] select user. id: %v, user: %v\n", id, user)
userMap[id] = user
}
}
}
return userMap
}
func TestBatchSelectUser() {
var ids []int
userNum := 100
for i := 0; i < userNum; i++ {
ids = append(ids, 10000+i)
}
users := BatchSelectUser(ids)
fmt.Println(users[10005])
fmt.Println(users[10020])
}