go动态配置apollo
dio 2020-07-01 go
# 配置文件 app.properties
{
"appId": "smart-hr",
"cluster": "dev",
"namespaceName": "application",
"ip": "http://127.0.0.1:18080",
"backupConfigPath":"",
"secret":"49a856b4f45446fdbe20355e592e8439"
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 代码demo
package main
import (
"fmt"
"log"
"strings"
"github.com/apolloconfig/agollo/v4"
apollolog "github.com/apolloconfig/agollo/v4/component/log"
"github.com/apolloconfig/agollo/v4/env"
"github.com/apolloconfig/agollo/v4/env/config"
"github.com/apolloconfig/agollo/v4/storage"
)
type ChangeListener struct {
}
func main() {
//读取环境中apollo配置
appcfg := env.InitFileConfig()
if appcfg == nil {
return
}
//初始化apollo中日志
agollo.SetLogger(&apollolog.DefaultLogger{})
//根据apollo配置,得到apollo client
client, _ := agollo.StartWithConfig(func() (*config.AppConfig, error) {
return appcfg, nil
})
//设置监听对象
c := &ChangeListener{}
//添加监听
client.AddChangeListener(c)
log.Println("init success")
//初次读取配置
FromApoloSet(client, appcfg)
select {}
}
func FromApoloSet(client agollo.Client, c *config.AppConfig) {
namespaces := strings.Split(c.NamespaceName, ",")
for _, namespace := range namespaces {
cache := client.GetConfigCache(namespace)
//日志设置
level, _ := cache.Get("log.level")
fmt.Println(level)
path, _ := cache.Get("log.path")
fmt.Println(path)
//设置kafka
addrs, _ := cache.Get("kafka.addrs")
fmt.Println(addrs)
topic, _ := cache.Get("kafka.topic")
fmt.Println(topic)
num, _ := cache.Get("kafka.producernum")
fmt.Println(num)
}
}
func (c *ChangeListener) OnChange(changeEvent *storage.ChangeEvent) {
}
func (c *ChangeListener) OnNewestChange(event *storage.FullChangeEvent) {
//write your code here
appcfg := env.InitFileConfig()
if appcfg == nil {
return
}
namespaces := strings.Split(appcfg.NamespaceName, ",")
namespacemap := make(map[string]bool)
for _, namespace := range namespaces {
namespacemap[namespace] = true
}
//检查想监听的配置
if _, ok := namespacemap[event.Namespace]; ok {
newlogleve, ok := event.Changes["log.level"]
if ok {
newloglevel, _ := newlogleve.(string)
fmt.Println(newloglevel)
}
}
if _, ok := namespacemap[event.Namespace]; ok {
newlogleve, ok := event.Changes["kafka.topic"]
if ok {
newloglevel, _ := newlogleve.(string)
fmt.Println(newloglevel)
}
}
}
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
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