-
Notifications
You must be signed in to change notification settings - Fork 14
/
nacos_manager.go
100 lines (89 loc) · 2.52 KB
/
nacos_manager.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
package nacos_viper_remote
import (
"fmt"
"github.com/nacos-group/nacos-sdk-go/clients"
"github.com/nacos-group/nacos-sdk-go/clients/config_client"
"github.com/nacos-group/nacos-sdk-go/common/constant"
"github.com/nacos-group/nacos-sdk-go/common/logger"
"github.com/nacos-group/nacos-sdk-go/vo"
"github.com/spf13/viper"
"strings"
)
type nacosConfigManager struct {
client config_client.IConfigClient
option *Option
}
func NewNacosConfigManager(option *Option) (*nacosConfigManager, error) {
var serverConfigs []constant.ServerConfig
urls := strings.Split(option.Url, ";")
for _, url := range urls {
serverConfigs = append(serverConfigs, constant.ServerConfig{
ContextPath: "/nacos",
IpAddr: url,
Port: option.Port,
})
}
clientConfig := constant.ClientConfig{
NamespaceId: option.NamespaceId,
TimeoutMs: 5000,
NotLoadCacheAtStart: true,
RotateTime: "1h",
MaxAge: 3,
LogLevel: "info",
}
if option.Auth != nil && option.Auth.Enable {
clientConfig.Username = option.Auth.User
clientConfig.Password = option.Auth.Password
clientConfig.Endpoint = option.Auth.Endpoint
clientConfig.RegionId = option.Auth.RegionId
clientConfig.AccessKey = option.Auth.AccessKey
clientConfig.SecretKey = option.Auth.SecretKey
clientConfig.OpenKMS = option.Auth.OpenKMS
}
client, err := clients.CreateConfigClient(map[string]interface{}{
"serverConfigs": serverConfigs,
"clientConfig": clientConfig,
})
if err != nil {
logger.Error(err.Error())
return nil, err
}
manager := &nacosConfigManager{client: client, option: option}
return manager, err
}
func (cm *nacosConfigManager) Get(dataId string) ([]byte, error) {
//get config
content, err := cm.client.GetConfig(vo.ConfigParam{
DataId: cm.option.Config.DataId,
Group: cm.option.GroupName,
})
return []byte(content), err
}
func (cm *nacosConfigManager) Watch(dataId string, stop chan bool) <-chan *viper.RemoteResponse {
resp := make(chan *viper.RemoteResponse)
configParams := vo.ConfigParam{
DataId: cm.option.Config.DataId,
Group: cm.option.GroupName,
OnChange: func(namespace, group, dataId, data string) {
fmt.Println("config changed group:" + group + ", dataId:" + dataId)
resp <- &viper.RemoteResponse{
Value: []byte(data),
Error: nil,
}
},
}
err := cm.client.ListenConfig(configParams)
if err != nil {
return nil
}
go func() {
for {
select {
case <-stop:
_ = cm.client.CancelListenConfig(configParams)
return
}
}
}()
return resp
}