package main
import (
"fmt"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
"log"
"os"
"path"
"time"
)
var Cfg EnvSD
type EnvSD struct {
Mysql Mysql `mapstructure:"mysql"`
Consul Consul `mapstructure:"consul"`
}
type Mysql struct {
Conn string `mapstructure:"conn"`
Desc string `mapstructure:"desc"`
Auth `mapstructure:",squash"`
}
type Consul struct {
Addr string `mapstructure:"addr"`
Desc string `mapstructure:"desc"`
Auth `mapstructure:",squash"`
}
type Auth struct {
User string `mapstructure:"user"`
Password string `mapstructure:"password"`
}
func initConf ( ) {
exePath, _ := os. Executable ( )
projectPath := path. Dir ( exePath)
viper. NewWithOptions ( viper. KeyDelimiter ( "->" ) )
viper. AddConfigPath ( projectPath)
viper. SetConfigName ( "conf.yaml" )
viper. SetConfigType ( "yaml" )
if err := viper. ReadInConfig ( ) ; err != nil {
log. Fatalln ( "[pkg.class.func.read config failed] " , err. Error ( ) )
}
viper. Unmarshal ( & Cfg)
fmt. Printf ( "%+v\n" , Cfg)
}
func watchFileUpdateConf ( ) {
viper. WatchConfig ( )
viper. OnConfigChange ( func ( e fsnotify. Event) {
viper. Unmarshal ( & Cfg)
log. Println ( e. String ( ) )
log. Printf ( "%+v\n" , Cfg)
} )
}
func main ( ) {
initConf ( )
go watchFileUpdateConf ( )
viper. Set ( "consul.addr" , "9.9.9.9" )
viper. UnmarshalKey ( "consul.addr" , "9.9.9.9" )
viper. WriteConfig ( )
time. Sleep ( 60 * time. Second)
}
远程读取 consul kv 库
package main
import (
"fmt"
"github.com/spf13/viper"
_ "github.com/spf13/viper/remote"
)
func main ( ) {
err := viper. AddRemoteProvider ( "consul" , "http://service-epoch-cozzc:8500" , "/test/server.json" )
if err != nil {
fmt. Println ( err. Error ( ) )
}
viper. SetConfigType ( "json" )
err = viper. ReadRemoteConfig ( )
if err != nil {
fmt. Println ( err. Error ( ) )
}
fmt. Println ( viper. GetString ( "server.ip" ) )
fmt. Println ( viper. GetString ( "server.port" ) )
}
watch机制
本地是用ionotify实现的 远程暂时只支持etcd, 使用轮询实现
参考链接
http://www.manongjc.com/detail/54-fdqfrlykcewpwsq.html)