golang中的配置管理库viper

viper简介

Viper是适用于Go应用程序的完整配置解决方案。它旨在在应用程序中工作,并且可以处理所有类型的配置需求和格式。它支持:

设置默认值
从JSON,TOML,YAML,HCL,envfile和Java属性配置文件中读取
实时观看和重新读取配置文件(可选)
从环境变量中读取
从远程配置系统(etcd或Consul)中读取,并观察更改
从命令行标志读取
从缓冲区读取
设置显式值
可以将Viper视为满足您所有应用程序配置需求的注册表。

加载配置优先级

Viper会按照下面的优先级。每个项目的优先级都高于它下面的项目:

显示调用Set设置值
命令行参数(flag)
环境变量
配置文件
key/value存储
默认值

目录结构

config.yaml

db:
  username: mayanan
  password: 123456789
  host: 123.123.12.123
  port: 33066
  database: docker01
v: 88.88  # 将会覆盖: v.SetDefault("V", "1.11")  // 建立默认值
version: 99.99

config.go

package config

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"os"
)

func LoadConfigFromYaml() (v *viper.Viper, err error) {
	v = viper.New()
	v.SetConfigName("config.yaml")
	v.AddConfigPath("./config/")
	v.SetConfigType("yaml")
	v.Set("version", "2.22")  // 显示调用Set设置值
	v.SetDefault("V", "1.11")  // 建立默认值

	// viper从环境变量读取
	v.SetEnvPrefix("spf")
	v.BindEnv("id")
	os.Setenv("spf_id", "111")

	if err = v.ReadInConfig(); err != nil {
		if _, ok := err.(viper.ConfigFileNotFoundError); ok {
			// Config file not found; ignore error if desired
			fmt.Println("Config file not found; ignore error if desired")
		} else {
			// Config file was found but another error was produced
			fmt.Println("Config file was found but another error was produced")
		}
	}

	// 监控配置和重新获取配置
	v.WatchConfig()

	v.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("Config file changed:", e.Name)
	})
	return v, err
}

main.go

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"viperTest/config"
)

func main() {
	router := gin.Default()
	v, _ := config.LoadConfigFromYaml()
	router.GET("/", func(context *gin.Context) {
		context.JSON(200, gin.H{
			"config": v.AllSettings(),
		})
		fmt.Println(v.GetString("db.password"), v.Get("id"))  // 获取单个配置属性
	})
	router.Run("127.0.0.1:8899")
}

获取值

在Viper中,根据值的类型,有几种获取值的方法。存在以下功能和方法:

Get(key string) : interface{}
GetBool(key string) : bool
GetFloat64(key string) : float64
GetInt(key string) : int
GetIntSlice(key string) : []int
GetString(key string) : string
GetStringMap(key string) : map[string]interface{}
GetStringMapString(key string) : map[string]string
GetStringSlice(key string) : []string
GetTime(key string) : time.Time
GetDuration(key string) : time.Duration
IsSet(key string) : bool
AllSettings() : map[string]interface{}

postman请求接口

http://127.0.0.1:8899
响应:

{
    "config": {
        "db": {
            "database": "docker01",
            "host": "123.123.12.123",
            "password": 123456,
            "port": 33066,
            "username": "mayanan"
        },
        "v": "1.11",
        "version": "2.22"
    }
}

此时把config.yaml中的内容改一下,再次请求接口,响应发生变化,根本不用重启我们的应用程序,非常的友好

写入配置文件

从配置文件中读取配置文件是有用的,但是有时你想要存储在运行时所做的所有修改。为此,可以使用下面一组命令,每个命令都有自己的用途:

WriteConfig - 将当前的viper配置写入预定义的路径并覆盖(如果存在的话)。如果没有预定义的路径,则报错。
SafeWriteConfig - 将当前的viper配置写入预定义的路径。如果没有预定义的路径,则报错。如果存在,将不会覆盖当前的配置文件。
WriteConfigAs - 将当前的viper配置写入给定的文件路径。将覆盖给定的文件(如果它存在的话)。
SafeWriteConfigAs - 将当前的viper配置写入给定的文件路径。不会覆盖给定的文件(如果它存在的话)。
根据经验,标记为safe的所有方法都不会覆盖任何文件,而是直接创建(如果不存在),而默认行为是创建或截断。
小示例:

viper.WriteConfig() // 将当前配置写入“viper.AddConfigPath()”和“viper.SetConfigName”设置的预定义路径
viper.SafeWriteConfig()
viper.WriteConfigAs("/path/to/my/.config")
viper.SafeWriteConfigAs("/path/to/my/.config") // 因为该配置文件写入过,所以会报错
viper.SafeWriteConfigAs("/path/to/my/.other_config")

viper中使用环境变量

Viper 完全支持环境变量。这使得12因素的应用程序开箱即用。有五种方法可以帮助与 ENV 合作:

AutomaticEnv()  // 可以通过v读取:v.Get("id")
BindEnv(string...) : error  // 绑定到viper中,既可以通过v读取,也可以通过v拿到配置
SetEnvPrefix(string)
SetEnvKeyReplacer(string...) *strings.Replacer
AllowEmptyEnv(bool)

viper简介
github.com/spf13/viper

viper配置文件映射到结构体

type ServerConfig struct {
	ServiceName string `mapstructure:"name"`
	Port int `mapstructure:"port"`
}

func main() {
	v := viper.New()

	//v.SetConfigName("config.yaml")
	//v.SetConfigType("yaml")
	//v.AddConfigPath("./")

	// 文件的路径如何设置
	v.SetConfigFile("config.yaml")  // 这一行跟上面三行功能实现相同

	err := v.ReadInConfig()
	if err != nil {
		panic(err)
	}
	fmt.Println(v.GetString("name"))

	// 将配置文件映射到结构体
	var serverConfig ServerConfig
	if err = v.Unmarshal(&serverConfig); err != nil {
		panic("config unmarshal failed")
	}
	fmt.Println(serverConfig)

}

viper配置文件映射到嵌套结构体

点击查看代码
type MysqlConfig struct {
	Host string `mapstructure:"host"`
	Port int `mapstructure:"port"`
}

type ServerConfig struct {
	ServiceName string `mapstructure:"name"`
	MysqlInfo MysqlConfig `mapstructure:"mysql"`
}

func main() {
	v := viper.New()

	//v.SetConfigName("config.yaml")
	//v.SetConfigType("yaml")
	//v.AddConfigPath("./")

	// 文件的路径如何设置
	v.SetConfigFile("config.yaml")  // 这一行跟上面三行功能实现相同

	err := v.ReadInConfig()
	if err != nil {
		panic(err)
	}
	fmt.Println(v.GetString("name"))
	ret := v.Get("mysql").(map[string]interface{})  // 将接口类型转换成map类型
	fmt.Println(ret["host"], ret["port"])


	// 将配置文件映射到结构体
	var serverConfig ServerConfig
	if err = v.Unmarshal(&serverConfig); err != nil {
		panic("config unmarshal failed")
	}
	fmt.Println(serverConfig, serverConfig.ServiceName, serverConfig.MysqlInfo.Host, serverConfig.MysqlInfo.Port)

}

viper配置开发环境和生产环境隔离

viper动态监控配置文件的变化

点击查看代码
// 不用改任何代码,而且线上和线下的代码能隔离开

func GetEnvInfo(env string) bool {
	viper.AutomaticEnv()
	return viper.GetBool(env)
	// 刚才设置的环境变量想要生效,我们必须得重启所有goland
}

type MysqlConfig struct {
	Host string `mapstructure:"host"`
	Port int `mapstructure:"port"`
}

type ServerConfig struct {
	ServiceName string `mapstructure:"name"`
	MysqlInfo MysqlConfig `mapstructure:"mysql"`
}

func main() {
	// 配置文件开发环境和生产环境隔离
	debugMode := GetEnvInfo("MXSHOP_DEBUG")
	var configFilePrefix = "config"
	var configFileName = fmt.Sprintf("%s_pro.yaml", configFilePrefix)
	if debugMode {
		configFileName = fmt.Sprintf("%s_dev.yaml", configFilePrefix)
	}

	v := viper.New()

	//v.SetConfigName("config_dev.yaml")
	//v.SetConfigType("yaml")
	//v.AddConfigPath("./")

	// 文件的路径如何设置
	v.SetConfigFile(configFileName)

	err := v.ReadInConfig()
	if err != nil {
		panic(err)
	}
	fmt.Println(v.GetString("name"))
	ret := v.Get("mysql").(map[string]interface{})  // 将接口类型转换成map类型
	fmt.Println(ret["host"], ret["port"])

	// 将配置文件映射到结构体
	var serverConfig ServerConfig
	if err = v.Unmarshal(&serverConfig); err != nil {
		panic("config unmarshal failed")
	}
	fmt.Println(serverConfig, serverConfig.ServiceName, serverConfig.MysqlInfo.Host, serverConfig.MysqlInfo.Port)

	// viper的功能,动态监控变化
	v.WatchConfig()
	v.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("config file changed", e.Name)
		_ = v.ReadInConfig()
		_ = v.Unmarshal(&serverConfig)
		fmt.Println(serverConfig)
	})

	time.Sleep(time.Second * 300)

}


posted @ 2022-01-17 14:42  专职  阅读(943)  评论(0编辑  收藏  举报