config

package
v1.5.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2024 License: Apache-2.0 Imports: 13 Imported by: 7

README

config包

config包主要用于加载和管理项目中配置文件中的内容,配置文件为"application"开头的格式

1. 配置文件路径

默认该文件与main函数所在的类同目录

// 示例
- application.yml
- application-local.yml

2. 配置文件格式

支持yaml、yml、json、properties配置文件 优先级: json > properties > yaml > yml

3. 支持profile加载不同配置文件

格式:application-{profile}.yyy 其中profile对应的变量为:base.profiles.active 变量的设置可以有如下

  • 本地配置
  • 环境变量配置

优先级:环境变量 > 本地配置

img.png

代码中读取指定环境配置
// 配置环境
os.Setenv("base.profiles.active", "local")

// 然后再加载的时候就会加载local的配置文件
config.LoadConfig()

或者:直接加载对应{profile}的文件

// 配置环境
config.LoadFile("./application-local.yaml")

也支持叠加

// 配置环境
config.LoadFile("./application-local.yaml")
config.AppendFile("./application-append.yaml")

4. 支持直接获取配置值

config包中提供了各种类型的api,方便实时获取

// 基本类型
config.getValueInt("xxx.xxx")
config.getValueInt32("xxx.xxx")
config.getValueInt64("xxx.xxx")
config.getValueBool("xxx.xxx")
config.getValueString("xxx.xxx")
// ...

// 结构类型
config.getValueObject("xxx.xxx", &xxx)

示例:

var ServerCfg ServerConfig

// base前缀
type BaseConfig struct {
    Application AppApplication
    Data string
}

type AppApplication struct {
    Name string
}
base:
  application:
    name: "xxx-local"
  data: "test"
// 直接读取即可
config.getValueObject("base", &ServerCfg)

说明: v1.0.12版本后,支持对配置的中划线支持,此外还支持更多配置

  • 中划线:比如:data-base-user
  • 小驼峰:比如:dataBaseUser
  • 大驼峰:比如:DataBaseUser
  • 下划线:比如:data_base_user

比如:

key1:
  ok1:
    hao-de-ok: 12
    name-age: 32
  ok2:
    haoDeOk: 12
    nameAge: 32
  ok3:
    HaoDeOk: 12
    NameAge: 32
  ok4:
    hao_de_ok: 12
    name_age: 32
type SmallEntity struct {
    HaoDeOk int
    NameAge int
}

// 可以读取到
func TestSmall(t *testing.T) {
    config.LoadConfig()

    entity1 := SmallEntity{}
    config.GetValueObject("key1.ok1", &entity1)
    assert.Equal(t, entity1.NameAge, 32)
    assert.Equal(t, entity1.HaoDeOk, 12)

    entity2 := SmallEntity{}
    config.GetValueObject("key1.ok2", &entity2)
    assert.Equal(t, entity2.NameAge, 32)
    assert.Equal(t, entity2.HaoDeOk, 12)

    entity3 := SmallEntity{}
    config.GetValueObject("key1.ok3", &entity3)
    assert.Equal(t, entity3.NameAge, 32)
    assert.Equal(t, entity3.HaoDeOk, 12)

    entity4 := SmallEntity{}
    config.GetValueObject("key1.ok4", &entity4)
    assert.Equal(t, entity4.NameAge, 32)
    assert.Equal(t, entity4.HaoDeOk, 12)
}

6. 支持配置的叠加,相对路径和绝对路径

在配置已经加载完毕后,需要对一些配置进行覆盖,比如运维这边有相关的需求时候

// 相对路径
config.AppendConfigFromRelativePath(xx)

// 绝对路径
config.AppendConfigFromAbsPath(xx)

7. 支持自动读取cm文件

应用启动会默认读取/home/{base.application.name}/config/application-default.yml对应的内容并覆盖应用的配置中

也支持环境变量配置 base.config.cm.path=xxx

示例:

// 也可以代码中配置
os.Setenv("base.config.cm.path", "./application-append.yaml")

8. 支持配置的在线查看以及实时变更

如下配置开启后,就可以在线查看应用的所有配置了

base:
  endpoint:
    # 配置的动态实时变更,默认关闭
    config:
      enable: true/false
// 查看应用所有配置
curl http://localhost:xxx/{api-prefix}/{api-module}/config/values

// 查看应用所有配置(yaml结构)
curl http://localhost:xxx/{api-prefix}/{api-module}/config/values/yaml

// 查看应用的某个配置
curl http://localhost:xxx/{api-prefix}/{api-module}/config/value/{key}

// 修改应用的配置
curl -X PUT http://localhost:xxx/{api-prefix}/{api-module}/config/update -d '{"key":"xxx", "value":"yyyy"}'

提示:
修改应用的配置会发送配置变更事件"event_of_config_change",如果想要对配置变更进行监听,请监听,示例:

func xxxx() {
    // 添加配置变更事件的监听,listener.EventOfConfigChange是内置的"event_of_config_change"
    listener.AddListener(listener.EventOfConfigChange, ConfigChangeListener)
}

func ConfigChangeListener(event listener.BaseEvent) {
    ev := event.(listener.ConfigChangeEvent)
    if ev.Key == "xxx" {
        value := ev.Value
        // 你的配置变更处理代码
    }
}

注意
  • 配置实体化
    • 无法动态的变更
    • 不支持默认配置
  • api实时调用
    • 配置可以动态的变更
    • 有默认的api

建议:配置使用时候建议使用config.GetXXXX()

其中动态变更只对api实时调用的方式有效


9. 支持配置的占位符

version > 1.4.13

place:
  name: "test"
  name2: "test2"

test:
  name: ${place.name}
  name2: ${place.name2}

格式支持:yml、yaml、json和properties

{
  "place":{
    "name":"test",
    "name2":"test2"
  },
  "test":{
    "name":"${place.name}",
    "name2":"${place.name2}"
  }
}
place.name=test
place.name2=test2
test.name=${place.name}
test.name2=${place.name2}
注意:

该版本暂时不支持非叶子节点数据,比如如下的就无法获取

place:
  name: "test"
  name2: "test2"

test:
  # 如下无法读取数据
  tt: ${place}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ApiModule string
View Source
var CurrentProfile = ""

Functions

func AppendConfigFromAbsPath added in v0.3.0

func AppendConfigFromAbsPath(fileName string)

func AppendConfigFromRelativePath added in v0.3.0

func AppendConfigFromRelativePath(fileName string)

func AppendFile added in v1.1.1

func AppendFile(filePath string)

func AppendJsonFile added in v0.3.0

func AppendJsonFile(filePath string)

func AppendPropertyFile added in v0.3.0

func AppendPropertyFile(filePath string)

func AppendValue added in v1.1.1

func AppendValue(propertiesNewValue string)

func AppendYamlFile added in v0.3.0

func AppendYamlFile(filePath string)

func ExistConfigFile added in v1.0.0

func ExistConfigFile() bool

func GetConfigDeepValues added in v1.3.0

func GetConfigDeepValues(c *gin.Context)

func GetConfigValue added in v0.3.0

func GetConfigValue(c *gin.Context)

func GetConfigValues added in v0.3.0

func GetConfigValues(c *gin.Context)

func GetValue added in v0.3.0

func GetValue(key string) any

func GetValueArray added in v1.0.0

func GetValueArray(key string) []any

func GetValueArrayInt added in v1.0.0

func GetValueArrayInt(key string) []int

func GetValueBool added in v0.3.0

func GetValueBool(key string) bool

func GetValueBoolDefault added in v0.3.0

func GetValueBoolDefault(key string, defaultValue bool) bool

func GetValueFloat32 added in v0.3.0

func GetValueFloat32(key string) float32

func GetValueFloat32Default added in v0.3.0

func GetValueFloat32Default(key string, defaultValue float32) float32

func GetValueFloat64 added in v0.3.0

func GetValueFloat64(key string) float64

func GetValueFloat64Default added in v0.3.0

func GetValueFloat64Default(key string, defaultValue float64) float64

func GetValueInt added in v0.3.0

func GetValueInt(key string) int

func GetValueInt16 added in v0.3.0

func GetValueInt16(key string) int16

func GetValueInt16Default added in v0.3.0

func GetValueInt16Default(key string, defaultValue int16) int16

func GetValueInt32 added in v0.3.0

func GetValueInt32(key string) int32

func GetValueInt32Default added in v0.3.0

func GetValueInt32Default(key string, defaultValue int32) int32

func GetValueInt64 added in v0.3.0

func GetValueInt64(key string) int64

func GetValueInt64Default added in v0.3.0

func GetValueInt64Default(key string, defaultValue int64) int64

func GetValueInt8 added in v0.3.0

func GetValueInt8(key string) int8

func GetValueInt8Default added in v0.3.0

func GetValueInt8Default(key string, defaultValue int8) int8

func GetValueIntDefault added in v0.3.0

func GetValueIntDefault(key string, defaultValue int) int

func GetValueObject added in v0.3.0

func GetValueObject(key string, targetPtrObj any) error

func GetValueString added in v0.3.0

func GetValueString(key string) string

func GetValueStringDefault added in v0.3.0

func GetValueStringDefault(key, defaultValue string) string

func GetValueUInt added in v0.3.0

func GetValueUInt(key string) uint

func GetValueUInt16 added in v0.3.0

func GetValueUInt16(key string) uint16

func GetValueUInt16Default added in v0.3.0

func GetValueUInt16Default(key string, defaultValue uint16) uint16

func GetValueUInt32 added in v0.3.0

func GetValueUInt32(key string) uint32

func GetValueUInt32Default added in v0.3.0

func GetValueUInt32Default(key string, defaultValue uint32) uint32

func GetValueUInt64 added in v0.3.0

func GetValueUInt64(key string) uint64

func GetValueUInt64Default added in v0.3.0

func GetValueUInt64Default(key string, defaultValue uint64) uint64

func GetValueUInt8 added in v0.3.0

func GetValueUInt8(key string) uint8

func GetValueUInt8Default added in v0.3.0

func GetValueUInt8Default(key string, defaultValue uint8) uint8

func GetValueUIntDefault added in v0.3.0

func GetValueUIntDefault(key string, defaultValue uint) uint

func LoadConfig

func LoadConfig()

func LoadConfigFromAbsPath added in v0.3.0

func LoadConfigFromAbsPath(resourceAbsPath string)

func LoadConfigFromRelativePath added in v0.3.0

func LoadConfigFromRelativePath(resourceAbsPath string)

func LoadFile added in v1.1.1

func LoadFile(filePath string)

func LoadJsonFile added in v0.3.0

func LoadJsonFile(filePath string)

func LoadPropertyFile added in v0.3.0

func LoadPropertyFile(filePath string)

func LoadSpringConfig added in v0.3.0

func LoadSpringConfig(AConfig any)

func LoadYamlConfig added in v0.3.0

func LoadYamlConfig(fileName string, AConfig any, handler func(data []byte, AConfig any) error) error

LoadYamlConfig read fileName from private path fileName,eg:application.yml, and transform it to AConfig note: AConfig must be a pointer

func LoadYamlConfigByAbsolutPath added in v0.3.0

func LoadYamlConfigByAbsolutPath(path string, AConfig any, handler func(data []byte, AConfig any) error) error

LoadYamlConfigByAbsolutPath read fileName from absolute path fileName,eg:/home/isc-gobase/application.yml, and transform it to AConfig note: AConfig must be a pointer

func LoadYamlFile added in v0.3.0

func LoadYamlFile(filePath string)

func SetValue added in v0.3.0

func SetValue(key string, value any)

func UpdateConfig added in v0.3.0

func UpdateConfig(c *gin.Context)

Types

type ApplicationProperty added in v0.3.0

type ApplicationProperty struct {
	ValueMap     map[string]any
	ValueDeepMap map[string]any
}

type BaseApi added in v1.0.0

type BaseApi struct {
	Prefix string `yaml:"prefix"` // api前缀
}

type BaseApplication added in v1.0.0

type BaseApplication struct {
	Name string `yaml:"name"` // 应用名字
}

type BaseConfig added in v0.3.0

type BaseConfig struct {
	Api         BaseApi         `yaml:"api"`
	Application BaseApplication `yaml:"application"`
	Server      BaseServer      `yaml:"server"`
	EndPoint    BaseEndPoint    `yaml:"endpoint"`
	Logger      BaseLogger      `yaml:"logger"`
	Profiles    BaseProfile     `yaml:"profiles"`
}

BaseConfig base前缀

var BaseCfg BaseConfig

type BaseEndPoint added in v1.0.0

type BaseEndPoint struct {
	Health EndPointHealth `yaml:"health"` // 健康检查[端点]
	Config EndPointConfig `yaml:"config"` // 配置管理[端点]
}

type BaseException added in v1.0.0

type BaseException struct {
	Print ExceptionPrint `yaml:"print"` // 异常返回打印
}

type BaseGin added in v1.0.0

type BaseGin struct {
	Mode string `yaml:"mode"` // 有三种模式:debug/release/test
}

type BaseLogger added in v1.0.0

type BaseLogger struct {
	Level string // 日志root级别:trace/debug/info/warn/error/fatal/panic,默认:info
	Path  string
	Time  LoggerTime  // 时间配置
	Color LoggerColor // 日志颜色
	Split LoggerSplit // 日志切分
	Dir   string
	Max   struct {
		History int
	}
	Console struct {
		WriteFile bool
	}
}

type BaseProfile added in v1.0.0

type BaseProfile struct {
	Active string `yaml:"active"`
}

type BaseServer added in v1.0.0

type BaseServer struct {
	Enable    bool          `yaml:"enable"`    // 是否启用
	Port      int           `yaml:"port"`      // 端口号
	Gin       BaseGin       `yaml:"gin"`       // web框架gin的配置
	Exception BaseException `yaml:"exception"` // 异常处理
}

type DatasourceConfig added in v1.4.5

type DatasourceConfig struct {
	Username   string
	Password   string
	Host       string
	Port       int
	DriverName string
	DbName     string
	SqlitePath string
}

---------------------------- base.datasource ----------------------------

type EmqxConfig added in v1.5.2

type EmqxConfig struct {
	Servers              []string
	ClientId             string
	Username             string
	Password             string
	CleanSession         bool
	Order                bool
	WillEnabled          bool
	WillTopic            string
	WillQos              byte
	WillRetained         bool
	ProtocolVersion      uint
	KeepAlive            int64
	PingTimeout          string
	ConnectTimeout       string
	MaxReconnectInterval string
	AutoReconnect        bool
	ConnectRetryInterval string
	ConnectRetry         bool
	WriteTimeout         string
	ResumeSubs           bool
	MaxResumePubInFlight int
	AutoAckDisabled      bool
}
var EmqxCfg EmqxConfig

type EmqxServer added in v1.5.2

type EmqxServer struct {
	User *EmqxServerUser // username and password information
	Host string          // host or host:port
}

type EmqxServerUser added in v1.5.2

type EmqxServerUser struct {
	Username string
	Password string
}

type EndPointConfig added in v1.0.0

type EndPointConfig struct {
	Enable bool `yaml:"enable"` // 是否启用
}

type EndPointHealth added in v1.0.0

type EndPointHealth struct {
	Enable bool `yaml:"enable"` // 是否启用
}

type EnvProperty added in v0.3.0

type EnvProperty struct {
	Key   string
	Value string
}

type EtcdConfig added in v1.4.5

type EtcdConfig struct {
	// etcd的服务ip:port列表
	Endpoints []string

	Username string
	Password string

	// 自动同步间隔:是用其最新成员更新端点的间隔;默认为0,即禁用自动同步;配置示例:1s、1000ms
	AutoSyncInterval string

	// 拨号超时:是指连接失败后的超时时间;配置示例:1s、1000ms
	DialTimeout string

	// 拨号保持连接时间:是客户端ping服务器以查看传输是否连接的时间;配置示例:1s、1000ms
	DialKeepAliveTime string

	// 拨号保持连接超时:是客户端等待响应保持连接探测的时间,如果在此时间内没有收到响应,则连接将被关闭;配置示例:1s、1000ms
	DialKeepAliveTimeout string

	// 拨号重试策略: 默认为空:表示默认不重试;1、2、3...表示重试多少次;always:表示一直重试
	DialRetry string

	// 最大呼叫:发送MSG大小是客户端请求发送的字节限制
	MaxCallSendMsgSize int

	// 最大调用recv MSG大小是客户端响应接收限制
	MaxCallRecvMsgSize int

	// 当设置拒绝旧集群时,将拒绝在过时的集群上创建客户端
	RejectOldCluster bool

	// 设置允许无流时将允许客户端发送keepalive ping到服务器没有任何活动流rp cs
	PermitWithoutStream bool
}
var EtcdCfg EtcdConfig

type ExceptionPrint added in v1.0.0

type ExceptionPrint struct {
	Enable  bool  `yaml:"enable"`  // 是否启用
	Exclude []int `yaml:"exclude"` // 排除的httpStatus;默认可不填
}

type LoggerColor added in v1.0.0

type LoggerColor struct {
	Enable bool `yaml:"enable"` // 是否启用
}

type LoggerConfig added in v0.3.0

type LoggerConfig struct {
	Level string `yaml:"level"`
	Path  string `yaml:"level"`
	Time  struct {
		Format string `yaml:"format"`
	} `yaml:"time"`
	Color struct {
		Enable bool `yaml:"enable"`
	} `yaml:"color"`
	Split struct {
		Enable bool  `yaml:"enable"`
		Size   int64 `yaml:"size"`
	} `yaml:"split"`
	Dir string `yaml:"dir"`
	Max struct {
		History int `yaml:"history"`
	} `yaml:"max"`
	Console struct {
		WriteFile bool `yaml:"writeFile"`
	} `yaml:"console"`
}

type LoggerSplit added in v1.0.0

type LoggerSplit struct {
	Enable bool  `yaml:"enable"` // 日志是否启用切分:true/false,默认false
	Size   int64 `yaml:"size"`   // 日志拆分的单位:MB
}

type LoggerTime added in v1.0.0

type LoggerTime struct {
	Format string `yaml:"format"` // 时间格式,time包中的内容,比如:time.RFC3339
}

type RedisClusterConfig added in v1.0.12

type RedisClusterConfig struct {
	// 节点地址
	Addrs []string
	// 最大重定向次数
	MaxRedirects int
	// 开启从节点的只读功能
	ReadOnly bool
	// 允许将只读命令路由到最近的主节点或从节点,它会自动启用 ReadOnly
	RouteByLatency bool
	// 允许将只读命令路由到随机的主节点或从节点,它会自动启用 ReadOnly
	RouteRandomly bool
}

type RedisConfig added in v1.0.12

type RedisConfig struct {
	Password string
	Username string

	// 单节点
	Standalone RedisStandaloneConfig
	// 哨兵
	Sentinel RedisSentinelConfig
	// 集群
	Cluster RedisClusterConfig

	// ----- 命令执行失败配置 -----
	// 命令执行失败时候,最大重试次数,默认3次,-1(不是0)则不重试
	MaxRetries int
	// (单位毫秒) 命令执行失败时候,每次重试的最小回退时间,默认8毫秒,-1则禁止回退
	MinRetryBackoff int
	// (单位毫秒)命令执行失败时候,每次重试的最大回退时间,默认512毫秒,-1则禁止回退
	MaxRetryBackoff int

	// ----- 超时配置 -----
	// (单位毫秒)超时:创建新链接的拨号超时时间,默认15秒
	DialTimeout int
	// (单位毫秒)超时:读超时,默认3秒,使用-1,使用-1则表示无超时,0的话是表示默认3秒
	ReadTimeout int
	// (单位毫秒)超时:写超时,默认是读超时3秒,使用-1,使用-1则表示无超时,0的话是表示默认3秒
	WriteTimeout int

	// ----- 连接池相关配置 -----
	// 连接池类型:fifo:true;lifo:false;和lifo相比,fifo开销更高
	PoolFIFO bool
	// 最大连接池大小:默认每个cpu核是10个连接,cpu核数可以根据函数runtime.GOMAXPROCS来配置,默认是runtime.NumCpu
	PoolSize int
	// 最小空闲连接数
	MinIdleConns int
	// (单位毫秒) 连接存活时长,默认不关闭
	MaxConnAge int
	// (单位毫秒)获取链接池中的链接都在忙,则等待对应的时间,默认读超时+1秒
	PoolTimeout int
	// (单位毫秒)空闲链接时间,超时则关闭,注意:该时间要小于服务端的超时时间,否则会出现拿到的链接失效问题,默认5分钟,-1表示禁用超时检查
	IdleTimeout int
	// (单位毫秒)空闲链接核查频率,默认1分钟。-1禁止空闲链接核查,即使配置了IdleTime也不行
	IdleCheckFrequency int
}

RedisConfig base.redis前缀

var RedisCfg RedisConfig

type RedisSentinelConfig added in v1.0.12

type RedisSentinelConfig struct {
	// 哨兵的集群名字
	Master string
	// 哨兵节点地址
	Addrs []string
	// 数据库节点
	Database int
	// 哨兵用户
	SentinelUser string
	// 哨兵密码
	SentinelPassword string
	// 将所有命令路由到从属只读节点。
	SlaveOnly bool
}

RedisSentinelConfig base.redis.sentinel

type RedisStandaloneConfig added in v1.0.12

type RedisStandaloneConfig struct {
	Addr     string
	Database int
	// 网络类型,tcp或者unix,默认tcp
	Network  string `match:"value={tcp, unix}"  errMsg:"network值不合法,只可为两个值:tcp和unix"`
	ReadOnly bool
}

RedisStandaloneConfig base.redis.standalone

type StorageConnectionConfig added in v0.3.0

type StorageConnectionConfig struct {
	Host       string `yaml:"host"`
	Port       int    `yaml:"port"`
	User       string `yaml:"user"`
	Password   string `yaml:"password"`
	Parameters string `yaml:"parameters"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL