93 lines
2.0 KiB
Go
93 lines
2.0 KiB
Go
package config
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"github.com/spf13/viper"
|
|
_ "github.com/spf13/viper/remote"
|
|
"github.com/zeromicro/go-zero/zrpc"
|
|
clientv3 "go.etcd.io/etcd/client/v3"
|
|
)
|
|
|
|
const (
|
|
TypeKey = "CONFIG_TYPE" // 配置文件类型
|
|
TypeEtcd = "etcd"
|
|
TypeEnv = "env"
|
|
|
|
Prefix = "/youtu/config/" // 配置文件前缀
|
|
EtcdAddrKey = "ETCD_ADDR"
|
|
)
|
|
|
|
type Redis struct {
|
|
Host string `json:"host"`
|
|
Password string `json:"password"`
|
|
}
|
|
|
|
type AppAccount struct {
|
|
AppId string `json:"appId"`
|
|
Secret string `json:"secret"`
|
|
Type string `json:"type"`
|
|
}
|
|
|
|
type Config struct {
|
|
RpcServerConf zrpc.RpcServerConf
|
|
Mode string
|
|
Mysql string
|
|
Redis []Redis
|
|
}
|
|
|
|
func init() {
|
|
viper.SetDefault(EtcdAddrKey, "192.168.0.47:2379")
|
|
viper.SetDefault(TypeKey, TypeEtcd)
|
|
}
|
|
|
|
func GetConfig(c *Config, serverName string) (err error) {
|
|
err = viper.AddRemoteProvider("etcd3", viper.GetString(EtcdAddrKey), Prefix+serverName+".rpc")
|
|
fmt.Println(Prefix + serverName + ".rpc")
|
|
if err != nil {
|
|
return
|
|
}
|
|
viper.SetConfigType("json") // because there is no file extension in a stream of bytes, supported extensions are "json", "toml", "yaml", "yml", "properties", "props", "prop", "env", "dotenv"
|
|
err = viper.ReadRemoteConfig()
|
|
if err != nil {
|
|
return
|
|
}
|
|
err = viper.Unmarshal(&c)
|
|
if err != nil {
|
|
return
|
|
}
|
|
c.RpcServerConf.Name = serverName + ".rpc"
|
|
c.RpcServerConf.ServiceConf.Mode = c.Mode
|
|
return
|
|
}
|
|
|
|
func SetConfig(b, serverName string) (err error) {
|
|
etcdCli, err := clientv3.NewFromURL(viper.GetString(EtcdAddrKey))
|
|
if err != nil {
|
|
return
|
|
}
|
|
_, err = etcdCli.Put(context.Background(), Prefix+serverName+".rpc", b)
|
|
return
|
|
}
|
|
|
|
// EtcdGetOneAndWatch 获取etcd配置并监听对应的key
|
|
func EtcdGetOneAndWatch(ctx context.Context, cli *clientv3.Client, key string, ch chan []byte) {
|
|
defer close(ch)
|
|
b, err := cli.Get(ctx, key)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
for _, kv := range b.Kvs {
|
|
ch <- kv.Value
|
|
}
|
|
resCh := cli.Watch(ctx, key)
|
|
for res := range resCh {
|
|
for _, event := range res.Events {
|
|
ch <- event.Kv.Value
|
|
}
|
|
}
|
|
|
|
return
|
|
}
|