-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatch_item.go
64 lines (56 loc) · 1.39 KB
/
watch_item.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
package goconfig
import (
"github.com/spf13/viper"
"reflect"
"sync"
)
type watchItem struct {
key string // 监控的键
lastViper *viper.Viper // 上次的配置viper格式
lastHash string // 上次配置的viper哈希
lastVal interface{} // 上次的配置
config *Config
}
func (w *watchItem) reload() {
w.lastViper = w.config.GetConfig().Sub(w.key)
w.lastVal = w.config.GetConfig().Get(w.key)
if w.lastViper != nil {
w.lastHash = genHash(w.lastViper)
}
}
func (w *watchItem) isChange() bool {
newVal := w.config.GetConfig().Get(w.key)
newViper := w.config.GetConfig().Sub(w.key)
if (newViper == nil || w.lastViper == nil) && newViper != w.lastViper {
// 如果均为空,可能是由于key对应的配置不是map,因此不能认为全为空表示不变
return true
}
if newViper != nil && w.lastViper != nil {
newHash := genHash(newViper)
return w.lastHash != newHash
}
// 处理均不是map的情况
return !reflect.DeepEqual(newVal, w.lastVal)
}
var (
watchItemPool = sync.Pool{New: func() any {
return &watchItem{}
}}
)
func acquireWatchItem() *watchItem {
x := watchItemPool.Get().(*watchItem)
x.key = ""
x.lastViper = nil
x.lastHash = ""
x.lastVal = nil
x.config = nil
return x
}
func freeWatchItem(item *watchItem) {
watchItemPool.Put(item)
}
func freeWatchItemMap(m map[string]*watchItem) {
for _, x := range m {
freeWatchItem(x)
}
}