forked from davyxu/golog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasync.go
96 lines (71 loc) · 1.39 KB
/
async.go
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
package golog
import (
"os"
"sync"
"time"
)
const (
// 缓冲队列长度
asyncBufferSize = 100
// 开启内存池范围的写入大小
maxTextBytes = 1024
)
var (
asyncWriteBuff chan interface{}
asyncContextPool *sync.Pool
)
// 开启异步写入模式
func EnableASyncWrite() {
asyncWriteBuff = make(chan interface{}, asyncBufferSize)
asyncContextPool = new(sync.Pool)
// 拷贝数据的池
asyncContextPool.New = func() interface{} {
return make([]byte, maxTextBytes)
}
go func() {
for {
// 从队列中获取一个要写入的日志
raw := <-asyncWriteBuff
switch d := raw.(type) {
case func():
d()
case []byte:
// 写入目标
globalWriter.Write(d)
// 必须是由pool分配的,才能用池释放
if cap(d) < maxTextBytes {
asyncContextPool.Put(d)
}
}
}
}()
}
// 等待异步写入全部完成
func FlushASyncWrite(timeout time.Duration) {
if asyncWriteBuff == nil {
return
}
ch := make(chan struct{})
asyncWriteBuff <- func() {
// 确保文件已经写入
if f, ok := globalWriter.(*os.File); ok {
f.Sync()
}
ch <- struct{}{}
}
select {
case <-ch:
case <-time.After(timeout):
}
}
func queuedWrite(b []byte) {
var newb []byte
// 超大
if len(b) >= maxTextBytes {
newb = make([]byte, len(b))
} else {
newb = asyncContextPool.Get().([]byte)[:len(b)]
}
copy(newb, b)
asyncWriteBuff <- newb
}