config 配置插件
概述
业务配置是供业务使用的配置,它由业务程序定义配置的格式,含义和参数范围,trpc 框架并不使用业务配置,也不关心配置的含义。框架仅仅关心如何获取配置内容,解析配置,发现配置变化并告知业务程序。
框架通过定义组件化的配置接口抽象:trpc-go/config,集成基本的配置中心拉取能力,提供了一种简单方式读取多种内容源、多种文件类型的配置,具体配置实现通过插件注册进来。
业务配置也支持本地文件,这也是 trpc-go 原生支持配置插件,支持按文件粒度的读取和变更监听。
业务配置支持从多种数据源获取配置,比如:本地文件,配置中心,数据库等。
trpc 建议使用配置中心管理业务配置,而不是以本地文件的形式,使用配置中心有以下优点:
- 避免源代码泄露敏感信息
- 服务动态更新配置
- 多服务共享配置,避免一份配置拥有多个副本
- 支持灰度发布,配置回滚,拥有完善的权限管理和操作日志

核心接口
为了实现配置读写 、配置监听 和配置解析 ,trpc 如下接口,在需要拓展配置源时可自定义:
1、文件粒度操作接口
go
// DataProvider 数据提供者
// 支持按文件粒度的读取和监听, 实现接口后需要把实现的 DataProvider 注册到 config.RegisterProvider 内
// 原生支持的实现为 FileProvider
type DataProvider interface {
Name() string
Read(string) ([]byte, error)
Watch(ProviderCallback)
}
go
// Unmarshaler定义配置文件的内容要如何解析进行序列化
// 将二进制的文件流解析为go对象(原生支持有json/yaml/toml等格式)
// 自定义实现后需要把 Unmarshaler 注册到 config.RegisterUnmarshaler 内
type Unmarshaler interface {
Unmarshal(data []byte, value interface{}) error
}
2、配置项 kv 读取操作接口
go
// Config 定义了针对一个配置文件如何进行配置项(一般为kv)的读取
type Config interface {
Load() error
Reload()
Get(string, interface{}) interface{}
Unmarshal(interface{}) error
IsSet(string) bool
GetInt(string, int) int
GetInt32(string, int32) int32
GetInt64(string, int64) int64
GetUint(string, uint) uint
GetUint32(string, uint32) uint32
GetUint64(string, uint64) uint64
GetFloat32(string, float32) float32
GetFloat64(string, float64) float64
GetString(string, string) string
GetBool(string, bool) bool
Bytes() []byte
}
3、配置项监听接口
go
// KVConfig kv 配置
// 定义可监听 kv 变化的配置类, 自定义实现后需要把 KVConfig 注册到 config.Register 内以便外部获取
type KVConfig interface {
KV
Watcher
Name() string
}
// 监控接口定义
type Watcher interface {
// Watch 监听配置项 key 的变更事件
// 这里的"key"不一定是 `kv` 的键,而是配置中心的监听单位,比如 `tconf` 监听的就是一个文件, 而 `consul` 监听单位是单个 `kv`
Watch(ctx context.Context, key string, opts ...Option) (<-chan Response, error)
}
// Response 配置中心响应
type Response interface {
// Value 获取配置项对应的值
Value() string
// MetaData 额外元数据信息
// 配置 Option 选项,可用于承载不同配置中心的额外功能实现,例如 namespace,group, 租约等概念
MetaData() map[string]string
// Event 获取 Watch 事件类型
Event() EventType
}
// EventType 监听配置变更的事件类型
type EventType uint8
const (
// EventTypeNull 空事件
EventTypeNull EventType = 0
// EventTypePut 设置或更新配置事件
EventTypePut EventType = 1
// EventTypeDel 删除配置项事件
EventTypeDel EventType = 2
)
对外操作 API
由于实现配置中心方式有两种:DataProvider 和 KVConfig,在外层 API 使用上也是有所区分的。
go
//////// 基于 DataProvider 实现 ///////
// 指定 provider、yaml 格式、文件名加载配置
tcfg, err := config.Load("test.yaml", config.WithCodec("yaml"), config.WithProvider("file"))
cfg := newConfig()
tcfg.Unmarshal(cfg) // yaml格式解析为cfg内属性
config.GetProvider("file").Watch(func(key string, content []byte){
// 配置变更回调
// key为监听单元,content为变更后的配置
})
//////// 基于 KVConfig 实现 ///////
// 获取配置
resp, err := config.Get("etcd").Get("foo")
strConfig := resp.Value()
// 监听
ch, err := config.Get("etcd").Watch(context.Background(), "foo")
for rsp := range ch {
fmt.Println(rsp.Value())
}