config

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2026 License: MIT Imports: 5 Imported by: 2

README

Config

config 包定义了统一配置能力的核心契约,目标是让业务只依赖 go-micro/config,由 go-etcdgo-consulgo-k8s 提供具体实现。

设计目标

  • 统一配置模型,避免不同后端字段语义漂移
  • 统一存储与监听接口,降低后端切换成本
  • 统一选项与错误语义,减少重复治理逻辑
  • 支持运行时按上下文读取(TenantId/AppId/UserId)

目录说明

  • model.go:配置主键、配置内容、版本元数据、查询上下文、监听事件模型
  • store.go:统一存储接口
  • watch.go:统一监听接口
  • option.go:函数式配置选项与可插拔能力(Codec/Encryptor)
  • loader.go:统一配置加载入口,负责按 local / remote 方式加载基础配置,并支持从 Store 读取配置对象
  • error.go:统一错误定义

命名约定

  • BootstrapConf 是业务服务自己的启动配置模型,表示程序启动时只初始化一次的基础引导配置,这类配置通常不参与热更新
  • go-micro/config 不定义具体业务侧的 BootstrapConf 结构,而是提供通用加载能力,因此这里使用 loader 命名
  • LoaderParams + LoadConfig 用于描述“如何从 local / remote 加载一份基础配置”
  • StoreParams + LoadStoreConfig 用于描述“如何从统一配置存储中读取并解析一份配置”
  • 这样区分后,业务侧可以继续保留 BootstrapConf 语义,基础库侧则专注于加载过程,避免把“配置模型”和“加载动作”混在一起

使用方式

1) 实现 Store + Watcher

由各后端实现包完成:

  • go-etcd/config
  • go-consul/config
  • go-k8s/config
2) 业务侧依赖抽象

业务代码依赖 Store/Watcher 接口,不直接依赖具体后端实现。

3) 配置分层建议
  • 启动层:本地 BootstrapConf
  • 动态层:后端 watch 热更新
  • 场景层:按 TenantId/AppId/UserId 查询

最小示例

package main

import (
	"context"

	microcfg "github.com/fireflycore/go-micro/config"
)

func load(ctx context.Context, store microcfg.Store) (*microcfg.Item, error) {
	key := microcfg.Key{
		TenantId: "t1",
		Env:      "prod",
		AppId:    "order-service",
		Group:    "db",
		Name:     "primary",
	}
	return store.Get(ctx, key)
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrLocalLoaderIsNil 表示本地加载函数为空。
	ErrLocalLoaderIsNil = errors.New("config local loader is nil")
	// ErrRemoteLoaderIsNil 表示远程加载函数为空。
	ErrRemoteLoaderIsNil = errors.New("config remote loader is nil")
	// ErrPayloadDecoderIsNil 表示配置内容解码函数为空。
	ErrPayloadDecoderIsNil = errors.New("config payload decoder is nil")
	// ErrStoreIsNil 表示存储实现为空。
	ErrStoreIsNil = errors.New("config store is nil")
	// ErrWatcherIsNil 表示监听实现为空。
	ErrWatcherIsNil = errors.New("config watcher is nil")
	// ErrCodecIsNil 表示编解码实现为空。
	ErrCodecIsNil = errors.New("config codec is nil")
	// ErrEncryptorIsNil 表示加解密实现为空。
	ErrEncryptorIsNil = errors.New("config encryptor is nil")
	// ErrInvalidKey 表示配置键不合法。
	ErrInvalidKey = errors.New("invalid config key")
	// ErrInvalidItem 表示配置内容不合法。
	ErrInvalidItem = errors.New("invalid config item")
	// ErrResourceNotFound 表示配置资源不存在。
	ErrResourceNotFound = errors.New("config resource not found")
	// ErrVersionConflict 表示写入版本冲突。
	ErrVersionConflict = errors.New("config version conflict")
	// ErrUnsupportedLoadMode 表示配置加载模式不支持。
	ErrUnsupportedLoadMode = errors.New("unsupported config load mode")
)

Functions

func LoadConfig added in v1.3.0

func LoadConfig[T any](params LoaderParams, localLoad LocalLoaderFunc, remoteLoad RemoteLoaderFunc, payloadDecode PayloadDecodeFunc) (T, error)

LoadConfig 按 local / remote 规则加载并解析后端配置。

func LoadStoreConfig added in v1.3.0

func LoadStoreConfig[T any](ctx context.Context, store Store, params StoreParams, payloadDecode PayloadDecodeFunc) (T, error)

LoadStoreConfig 从 Store 读取当前配置并解析为目标类型 T。

Types

type Codec

type Codec interface {
	// Marshal 把结构化对象编码为字节。
	Marshal(v any) ([]byte, error)
	// Unmarshal 把字节解码到目标对象。
	Unmarshal(data []byte, dst any) error
}

Codec 定义配置内容序列化与反序列化能力。

type Encryptor

type Encryptor interface {
	// Encrypt 使用给定密钥加密数据。
	Encrypt(data []byte, key []byte) ([]byte, error)
	// Decrypt 使用给定密钥解密数据。
	Decrypt(data []byte, key []byte) ([]byte, error)
}

Encryptor 定义配置内容加解密能力。

type EventType

type EventType int

EventType 表示配置变更事件类型。

const (
	// EventPut 表示新增或更新事件。
	EventPut EventType = iota
	// EventDelete 表示删除事件。
	EventDelete
)

type Item

type Item struct {
	// Meta 记录扩展元信息。
	Meta map[string]string `json:"meta"`
	// Version 表示配置版本号。
	Version string `json:"version"`
	// Content 是配置原始内容。
	Content []byte `json:"content"`
	// Encrypted 标识 Content 是否已加密。
	Encrypted bool `json:"encrypted"`
	// UpdatedAt 表示最近更新时间。
	UpdatedAt time.Time `json:"updated_at"`
	// UpdatedBy 表示最近更新人。
	UpdatedBy string `json:"updated_by"`
}

Item 表示一条可发布、可读取的配置内容。

type Key

type Key struct {
	// TenantId 表示租户标识,用于多租户隔离。
	TenantId string `json:"tenant_id"`
	// AppId 表示应用标识。
	AppId string `json:"app_id"`
	// Env 表示环境,如 dev/staging/prod。
	Env string `json:"env"`

	// Group 表示配置分组。
	Group string `json:"group"`
	// Name 表示具体配置名。
	Name string `json:"name"`
}

Key 描述一条配置在存储中的业务主键。

type LoaderParams added in v1.3.0

type LoaderParams struct {
	// LoadMode 指定加载模式:local / remote。
	LoadMode string
	// AppId 远程模式下用于定位配置所属应用。
	AppId string
	// AppSecret 远程模式下用于解密配置内容(如果是密文)。
	AppSecret []byte
	// Group 配置分组(如 database)。
	Group string
	// Key 配置名(如 consul / etcd / k8s)。
	Key string
	// FileName 本地模式下使用的文件名(如 consul.json)。
	FileName string
}

LoaderParams 描述加载后端配置对象所需参数。 该结构把 local / remote 两条加载链路的输入参数统一起来。

type LocalLoaderFunc added in v1.3.0

type LocalLoaderFunc func(fileName string, target any) error

LocalLoaderFunc 定义本地配置加载函数签名。 典型实现是按 fileName 读取配置文件并反序列化到 target。

type Meta

type Meta struct {
	// CurrentVersion 表示当前生效版本。
	CurrentVersion string `json:"current_version"`
	// LatestVersion 表示最新发布版本。
	LatestVersion string `json:"latest_version"`
}

Meta 表示一组配置的版本游标信息。

type Option

type Option func(*Options)

Option 表示函数式配置项。

func WithCodec

func WithCodec(codec Codec) Option

WithCodec 注入自定义编解码实现。

func WithEncryptor

func WithEncryptor(encryptor Encryptor) Option

WithEncryptor 注入自定义加解密实现。

func WithNamespace

func WithNamespace(namespace string) Option

WithNamespace 设置配置命名空间。

func WithRetry

func WithRetry(retry uint32) Option

WithRetry 设置失败重试次数。

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout 设置单次请求超时时间。

func WithWatchBuffer

func WithWatchBuffer(size int) Option

WithWatchBuffer 设置监听事件缓冲区大小。

type Options

type Options struct {
	// Namespace 用于区分配置键空间。
	Namespace string
	// Timeout 用于单次请求超时控制。
	Timeout time.Duration
	// Retry 用于失败重试次数控制。
	Retry uint32
	// WatchBuffer 用于监听事件通道缓冲区大小。
	WatchBuffer int
	// Codec 为可选编解码器。
	Codec Codec
	// Encryptor 为可选加解密器。
	Encryptor Encryptor
}

Options 定义 config 组件的通用运行参数。

func NewOptions

func NewOptions(opts ...Option) *Options

NewOptions 生成带默认值的 Options,并按顺序应用外部参数。

type PayloadDecodeFunc added in v1.3.0

type PayloadDecodeFunc func(content string, secret []byte, target any) error

PayloadDecodeFunc 定义配置内容解码函数签名。 用于处理密文场景(例如解密后再反序列化到 target)。

type Query

type Query struct {
	// Key 是基础配置键。
	Key Key `json:"key"`

	// UserId 表示请求上下文中的用户标识。
	UserId string `json:"user_id"`
	// AppId 表示请求上下文中的应用标识。
	AppId string `json:"app_id"`
	// TenantId 表示请求上下文中的租户标识。
	TenantId string `json:"tenant_id"`

	// Tags 表示额外标签条件。
	Tags map[string]string `json:"tags"`
}

Query 表示运行时按上下文查询配置的入参。

type RemoteLoaderFunc added in v1.3.0

type RemoteLoaderFunc func(appId, group, key string) (string, error)

RemoteLoaderFunc 定义远程配置读取函数签名。 典型实现是从配置中心按 appId + group + key 获取配置文本。

type Store

type Store interface {
	// Get 按配置键读取当前生效配置。
	Get(ctx context.Context, key Key) (*Item, error)
	// GetByQuery 按运行时上下文读取配置。
	GetByQuery(ctx context.Context, query Query) (*Item, error)
	// Put 写入当前生效配置。
	Put(ctx context.Context, key Key, item *Item) error
	// Delete 删除当前配置。
	Delete(ctx context.Context, key Key) error

	// PutVersion 写入版本快照并返回版本号。
	PutVersion(ctx context.Context, key Key, item *Item) (string, error)
	// GetVersion 读取指定版本快照。
	GetVersion(ctx context.Context, key Key, version string) (*Item, error)
	// ListVersions 列出版本号列表。
	ListVersions(ctx context.Context, key Key, limit int) ([]string, error)

	// GetMeta 读取配置元信息。
	GetMeta(ctx context.Context, key Key) (*Meta, error)
	// PutMeta 写入配置元信息。
	PutMeta(ctx context.Context, key Key, meta *Meta) error
}

Store 定义统一配置存储抽象,供 etcd/consul/k8s 实现对齐。

type StoreParams added in v1.3.0

type StoreParams struct {
	// Key 是优先使用的业务键。
	Key Key
	// AppId 用于回填 Key.AppId。
	AppId string
	// Env 用于回填 Key.Env。
	Env string
	// Group 用于回填 Key.Group。
	Group string
	// Name 用于回填 Key.Name。
	Name string
	// AppSecret 当读取到密文配置时用于解码。
	AppSecret []byte
}

StoreParams 描述从 Store 读取一条配置并解析所需参数。 当 Key 某些字段为空时,会用 AppId / Env / Group / Name 回填。

type WatchEvent

type WatchEvent struct {
	// Type 表示事件类型。
	Type EventType `json:"type"`
	// Key 表示事件对应的配置键。
	Key Key `json:"key"`
	// Item 表示事件携带的配置内容。
	Item *Item `json:"item"`
}

WatchEvent 表示 watch 通知事件。

type Watcher

type Watcher interface {
	// Watch 监听指定配置键的变更事件。
	Watch(ctx context.Context, key Key) (<-chan WatchEvent, error)
	// Unwatch 取消指定配置键的监听。
	Unwatch(key Key)
}

Watcher 定义统一配置监听抽象。

Jump to

Keyboard shortcuts

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