-
Notifications
You must be signed in to change notification settings - Fork 4
/
mdc.go
145 lines (126 loc) · 2.47 KB
/
mdc.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
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package over
import (
"fmt"
"strconv"
"sync"
)
var (
_globalMdc = InitGlobalMdcAdapter()
_MdcAdapter *MdcAdapter
)
type MdcAdapter struct {
items map[string]interface{}
sync.RWMutex
}
func InitGlobalMdcAdapter() *MdcAdapter {
if _MdcAdapter == nil {
_MdcAdapter = &MdcAdapter{items: make(map[string]interface{})}
}
return _MdcAdapter
}
func ResetGlobalMdcAdapter() {
_MdcAdapter.RLock()
_MdcAdapter.items = make(map[string]interface{})
_MdcAdapter.RUnlock()
}
func MDC() *MdcAdapter {
_MdcAdapter.RLock()
s := _globalMdc
_MdcAdapter.RUnlock()
return s
}
func (m *MdcAdapter) Set(key string, value interface{}) {
uniqueKey := m.getUniqueKey(key)
m.Lock()
m.items[uniqueKey] = value
m.Unlock()
}
func (m *MdcAdapter) SetMap(data map[string]interface{}) {
for key, value := range data {
uniqueKey := m.getUniqueKey(key)
m.Lock()
m.items[uniqueKey] = value
m.Unlock()
}
}
func (m *MdcAdapter) SetIfAbsent(key string, value interface{}) bool {
uniqueKey := m.getUniqueKey(key)
m.Lock()
_, ok := m.items[uniqueKey]
if !ok {
m.items[uniqueKey] = value
}
m.Unlock()
return !ok
}
func (m *MdcAdapter) Get(key string) (interface{}, bool) {
uniqueKey := m.getUniqueKey(key)
m.RLock()
v, ok := m.items[uniqueKey]
m.RUnlock()
return v, ok
}
func (m *MdcAdapter) GetString(key string) string {
uniqueKey := m.getUniqueKey(key)
m.RLock()
v, ok := m.items[uniqueKey]
m.RUnlock()
if !ok {
v = ""
}
return fmt.Sprintf("%v", v)
}
func (m *MdcAdapter) Count() int {
m.RLock()
count := len(m.items)
m.RUnlock()
return count
}
func (m *MdcAdapter) Has(key string) bool {
uniqueKey := m.getUniqueKey(key)
m.RLock()
_, ok := m.items[uniqueKey]
m.RUnlock()
return ok
}
func (m *MdcAdapter) Remove(key string) {
uniqueKey := m.getUniqueKey(key)
m.Lock()
delete(m.items, uniqueKey)
m.Unlock()
}
func (m *MdcAdapter) IsEmpty() bool {
m.RLock()
count := len(m.items)
m.RUnlock()
return count == 0
}
func (m *MdcAdapter) Keys() []string {
count := m.Count()
ch := make(chan string, count)
go func() {
wg := sync.WaitGroup{}
wg.Add(1)
go func(m *MdcAdapter) {
m.RLock()
for key := range m.items {
ch <- key
}
m.RUnlock()
wg.Done()
}(m)
wg.Wait()
close(ch)
}()
keys := make([]string, 0, count)
for k := range ch {
keys = append(keys, k)
}
return keys
}
func (m *MdcAdapter) getUniqueKey(key string) string {
if key == "" {
panic("MDC key cannot be empty")
}
return key + "-" + strconv.FormatUint(GetGoroutineID(), 10)
}