-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathcom.go
55 lines (46 loc) · 924 Bytes
/
com.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
package yago
import (
"io"
"log"
"sync"
)
type components struct {
m sync.Map
}
func (c *components) Ins(key string, f func() interface{}) interface{} {
// @todo 监听配置重载信号
v, ok := c.m.Load(key)
if !ok {
val := f()
v, _ = c.m.LoadOrStore(key, val)
}
return v
}
func (c *components) Del(key interface{}, cb ...func()) {
c.m.Delete(key)
if len(cb) > 0 {
// 执行回调关闭链接
go cb[0]()
}
}
func (c *components) clear() {
comKeys := make([]interface{}, 0)
c.m.Range(func(key, value interface{}) bool {
comKeys = append(comKeys, key)
return true
})
for _, key := range comKeys {
c.m.Delete(key)
}
}
func (c *components) Close() {
c.m.Range(func(key, value interface{}) bool {
if v, ok := value.(io.Closer); ok {
if err := v.Close(); err != nil {
log.Printf("Com %s close error: %s\n", key, err)
}
}
return true
})
}
var Component = new(components)