vade

package module
v0.0.0-...-88236ff Latest Latest
Warning

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

Go to latest
Published: May 25, 2020 License: Apache-2.0 Imports: 21 Imported by: 0

README

vade-go

分布式应用配置管理框架,从多种配置源中拉取配置转化为properties的格式进行管理,监听配置变更进行实时同步。

特性

  1. 多种配置源, 容易扩展。
  2. 自定义优先级。
  3. 多种配置格式, 默认支持json,yaml,properties格式。
  4. 支持变量替换,默认支持${}形式。
  5. 支持将配置Unmarshal到结构体或者map中。
  6. 支持配置覆盖或设置默认配置。
  7. 可Watch配置变更。

安装

go get -v github.com/derry6/vade-go

使用

1. 基本使用

func init() {
    // 定义命令行参数
    vade.Flag("vade.logging.level", "xx", "logging level")
    vade.Flag("a.b.c", 100, "abc")
}

type listener struct {

}
func (e *listener) OnPropertyEvent(ev *vade.Event) {
    log.Printf("Property changed: %v", ev.String())
}

func main() {
    requires := []string{"service.yaml"}
    optionals :=[]string{"logger.yaml"}
    // 初始化
    err := vade.Init(
        vade.WithFileSource(requires, optionals),
        vade.WithEnvSource(),
        vade.WithFlagSource())
    if err != nil {
        panic(err)
    }
    // 覆盖所有的配置
    vade.Set("time.now", time.Now().Format(time.RFC3339))

    values := vade.All()
    for k, v := range values {
       log.Printf("%s = %v", k, v)
    }
    log.Printf("time.now = %v", vade.MustTime("time.now").String())

    // Watch 配置的变更
    id := vade.Watch("^vade.logging.*$", &listener{})
    defer vade.Unwatch(id)
    select{}
}
2. 远程配置源
    // 初始化
    vade.Init()
    
    // 创建配置源客户端
    cfg := client.DefaultConfig()
    cfg.Address = "localhost:8848"
    cfg.Timeout = 3 * time.Second
    cli, _ := client.New("nacos", cfg)
    s := source.New("nacos", cli)
    // 添加配置
    _ = s.AddPath("test.yaml", source.WithPathRequired())
    
    _ = vade.AddSource(s)
3. 自定义变量替换
func doExpand(in string)(v interface{}, err error) {
    return "replaced-" + in ,nil
}

vade.Init(vade.WithExpansion("${", "}",doExpand))

4. Unmarshal
  1. 支持数据类型bool/int/float/string/map/struct/slice, 支持内嵌struct
  2. 支持指定tag, 默认使用yaml.
    type Value struct {
        Int    int                    `yaml:"int"`
        Float  float64                `yaml:"float"`
        Bool   bool                   `yaml:"bool"`
        String string                 `yaml:"string"`
        Map    map[string]interface{} `yaml:"map"`
        Slice  []string               `yaml:"slice"`
        Other  map[string]interface{} `yaml:",inline"`
    }
    // properties:
    /*
        abc.config.int
        abc.config.float
        abc.config.bool
        abc.config.string
        abc.config.map.a
        abc.config.map.b
        abc.config.slice[0] 
        abc.config.slice[1]
        abc.config.slice[2]
        abc.config.other1
        abc.config.other2
        abc.config.otherX
    */

    var v Value
    // Unmarshal value.* to v
    vade.Unmarshal(&v,vade.WithUnmarshalPrefix("abc.config"), vade.WithUnmarshalTag("yaml"))

参考

  1. https://github.com/spf13/viper
  2. https://github.com/magiconair/properties

Documentation

Index

Constants

View Source
const (
	DefaultFilePriority   = 0
	DefaultEnvPriority    = 1
	DefaultFlagPriority   = 3
	DefaultRemotePriority = 9
)

Variables

View Source
var (
	Created = source.Created
	Updated = source.Updated
	Deleted = source.Deleted
)

Event actions

Functions

func AddPath

func AddPath(source string, path string, opts ...source.PathOption) error

func AddSource

func AddSource(s source.Source) error

AddSource 添加source

func All

func All() map[string]interface{}

All 返回所有的kv

func Bool

func Bool(key string, def bool) bool

Bool 获取 bool 值

func Delete

func Delete(key string)

Delete 删除覆盖的key和默认key

func Duration

func Duration(key string, def time.Duration) time.Duration

Duration 获取 duration 值

func Flag

func Flag(key string, def interface{}, usage string)

Flag 定义命令行参数

func Float

func Float(key string, def float64) float64

Float 获取float值

func Get

func Get(key string) (value interface{}, ok bool)

Get 获取指定key的value, 不存在时ok为false

func Init

func Init(opts ...Option) (err error)

func Int

func Int(key string, def int) int

Int 获取int值

func Keys

func Keys() []string

Keys 返回所有的key

func MustBool

func MustBool(key string) bool

MustBool 获取 bool 值

func MustDuration

func MustDuration(key string) time.Duration

MustDuration 获取 duration 值

func MustFloat

func MustFloat(key string) float64

MustFloat 获取float值

func MustInt

func MustInt(key string) int

MustInt 获取int值

func MustString

func MustString(key string) string

MustString 获取 string 值

func MustTime

func MustTime(key string) time.Time

MustTime 获取 time 值

func Set

func Set(key string, value interface{})

Set 设置kv, 覆盖配置。

func SetDefault

func SetDefault(key string, value interface{})

SetDefault 设置默认值

func SetLogger

func SetLogger(logger log.Logger)

func Source

func Source(name string) (source.Source, error)

Source 返回指定名称的source, 或者错误

func Sources

func Sources() []source.Source

Sources 返回添加的所有source

func String

func String(key string, def string) string

fullKey 获取 string 值

func Time

func Time(key string, def time.Time) time.Time

Time 获取 time 值

func Unmarshal

func Unmarshal(out interface{}, opts ...UnmarshalOption) error

func Unwatch

func Unwatch(id int64)

Unwatch 取消监听

func Watch

func Watch(pattern string, cb EventHandler) (id int64)

Watch 监听某个满足pattern模式的key变化的事件。

Types

type Event

type Event = source.Event

Event property event

type EventHandler

type EventHandler interface {
	OnPropertyChange(events []*Event)
}

EventHandler 事件处理

type Manager

type Manager interface {
	// 添加配置源
	AddSource(src source.Source) error
	Source(name string) (source.Source, error)
	Sources() []source.Source

	AddPath(sourceName string, path string, opts ...source.PathOption) error

	// 配置kv相关操作
	All() (values map[string]interface{})
	Keys() (keys []string)
	Get(key string) (value interface{}, ok bool)
	Set(key string, value interface{})
	SetDefault(key string, value interface{})
	Delete(key string)

	// 监听事件
	Watch(pattern string, handler EventHandler) (watchId int64)
	Unwatch(id int64)
}

Manager 管理不同的 Source

func NewManager

func NewManager(opts ...Option) (Manager, error)

NewManager create manager instance

type Option

type Option func(opts *options)

func WithEnvSource

func WithEnvSource(sOpts ...source.Option) Option

func WithExpandDisabled

func WithExpandDisabled() Option

WithExpandDisabled 禁止变量替换

func WithExpansion

func WithExpansion(pre, post string, cb expander.Handler) Option

WithExpansion 指定需要变量替换的模板

func WithFileSource

func WithFileSource(requires, optionals []string, sOpts ...source.Option) Option

func WithFlagSource

func WithFlagSource(sOpts ...source.Option) Option

func WithLogger

func WithLogger(logger log.Logger) Option

func WithRemoteSource

func WithRemoteSource(name string, config *client.Config, sOpts ...source.Option) Option

type TypeError

type TypeError struct {
	Errors []string
}

func (*TypeError) Error

func (e *TypeError) Error() string

type UnmarshalGet

type UnmarshalGet func(key string) (value interface{}, ok bool)

type UnmarshalOption

type UnmarshalOption func(d *decoder)

func WithUnmarshalPrefix

func WithUnmarshalPrefix(key string) UnmarshalOption

func WithUnmarshalTag

func WithUnmarshalTag(tag string) UnmarshalOption

type Unmarshaler

type Unmarshaler interface {
	UnmarshalProps(unmarshal func(interface{}) error) error
}

Directories

Path Synopsis
example
pkg
log

Jump to

Keyboard shortcuts

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