forked from printfcoder/stack-rpc-tutorials
-
Notifications
You must be signed in to change notification settings - Fork 3
/
config.go
97 lines (75 loc) · 1.43 KB
/
config.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
package config
import (
"fmt"
"sync"
"github.com/micro/go-micro/v2/config"
log "github.com/micro/go-micro/v2/logger"
)
var (
m sync.RWMutex
inited bool
// 默认配置器
c = &configurator{}
)
// Configurator 配置器
type Configurator interface {
App(name string, config interface{}) (err error)
}
// configurator 配置器
type configurator struct {
conf config.Config
}
func (c *configurator) App(name string, config interface{}) (err error) {
v := c.conf.Get(name)
if v != nil {
err = v.Scan(config)
} else {
err = fmt.Errorf("[App] 配置不存在,err:%s", name)
}
return
}
// c 配置器
func C() Configurator {
return c
}
func (c *configurator) init(ops Options) (err error) {
m.Lock()
defer m.Unlock()
if inited {
log.Info("[init] 配置已经初始化过")
return
}
c.conf, _ = config.NewConfig()
// 加载配置
err = c.conf.Load(ops.Sources...)
if err != nil {
log.Fatal(err)
}
go func() {
log.Info("[init] 侦听配置变动 ...")
// 开始侦听变动事件
watcher, err := c.conf.Watch()
if err != nil {
log.Fatal(err)
}
for {
v, err := watcher.Next()
if err != nil {
log.Fatal(err)
}
log.Infof("[init] 侦听配置变动: %v", string(v.Bytes()))
}
}()
// 标记已经初始化
inited = true
return
}
// Init 初始化配置
func Init(opts ...Option) {
ops := Options{}
for _, o := range opts {
o(&ops)
}
c = &configurator{}
c.init(ops)
}