Skip to content

Conversation

@LanceAdd
Copy link
Member

@LanceAdd LanceAdd commented Dec 25, 2025

Configurator 配置管理器

Configurator 是一个通用的配置管理器,提供了类似于 Spring Boot 的@ConfigurationProperties的配置加载、监控、更新和管理功能。

功能特性

  • 泛型支持:使用 Go 泛型,类型安全的配置绑定
  • 配置加载:从配置源加载数据并绑定到结构体
  • 配置监控:自动监控配置变化并更新
  • 自定义转换器:支持自定义数据转换函数
  • 回调处理:配置变更时的回调函数
  • 错误处理:灵活的错误处理机制

安装

go get github.com/gogf/gf/v2

使用示例

1. 基本用法

用法一

package main

import (
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gcfg"
	"github.com/gogf/gf/v2/os/gctx"
)

type AppConfig struct {
	Name     string       `json:"name"`
	Age      int          `json:"age"`
	Enabled  bool         `json:"enabled"`
	Features []string     `json:"features"`
	Server   ServerConfig `json:"server"`
}

type ServerConfig struct {
	Host string `json:"host"`
	Port int    `json:"port"`
}

func main() {
	ctx := gctx.New()
	// 创建配置器实例
	configurator := gcfg.NewConfigurator[AppConfig](g.Cfg("test"), "")

	// 加载和监听配置
	configurator.MustLoadAndWatch(ctx, "test-watcher")

	// 获取配置
	config := configurator.Get()
	fmt.Println(config.Name)
}

用法二

package main

import (
	"fmt"
	"github.com/gogf/gf/v2/os/gcfg"
	"github.com/gogf/gf/v2/os/gctx"
)

type AppConfig struct {
	Name     string       `json:"name"`
	Age      int          `json:"age"`
	Enabled  bool         `json:"enabled"`
	Features []string     `json:"features"`
	Server   ServerConfig `json:"server"`
}

type ServerConfig struct {
	Host string `json:"host"`
	Port int    `json:"port"`
}

func main() {
	ctx := gctx.New()

	// 使用单独的适配器创建
	// 创建配置管理器
	cfg, _ := gcfg.NewAdapterFile("test.yaml")
	// 创建配置器实例
	configurator := gcfg.NewConfiguratorWithAdapter[AppConfig](cfg, "")

	// 加载和监听配置
	configurator.MustLoadAndWatch(ctx, "test-watcher")

	// 获取配置
	config := configurator.Get()
	fmt.Println(config.Name)
}

2. 配置监控

// 仅加载App配置
configurator := gcfg.NewConfiguratorWithAdapter[AppConfig](cfg, "app")

// 设置配置变更回调
configurator.OnChange(func(updated AppConfig) error {
    // 配置变更时的处理逻辑
    println("配置已更新:", updated.Name)
    return nil
})

// 加载数据
err := configurator.Load(ctx)
if err != nil {
    panic(err)
}

// 开始监控配置变化
err := configurator.Watch(context.Background(), "my-watcher")
if err != nil {
    panic(err)
}

3. 自定义转换器

// 设置自定义转换器
configurator.SetConverter(func(data any, target *AppConfig) error {
    // 自定义数据转换逻辑
    return nil
})

4. 便捷方法

// 一步完成加载和监控
configurator.MustLoadAndWatch(context.Background(), "my-app")

API 参考

NewConfigurator

创建一个新的 Configurator 实例。

func NewConfigurator[T any](config *Config, propertyKey string, targetStruct ...*T) *Configurator[T]

参数:

  • config: 配置实例,用于监控变化
  • propertyKey: 监控的属性键模式(使用 "" 或 "." 监控所有配置)
  • targetStruct: 接收配置值的结构体指针(可选)

NewConfiguratorWithAdapter

使用适配器创建一个新的 Configurator 实例。

func NewConfiguratorWithAdapter[T any](adapter Adapter, propertyKey string, targetStruct ...*T) *Configurator[T]

Load

从配置实例加载数据并绑定到目标结构体。

func (c *Configurator[T]) Load(ctx context.Context) error

MustLoad

与 Load 类似,但出错时会 panic。

func (c *Configurator[T]) MustLoad(ctx context.Context)

Watch

开始监控配置变化并自动更新目标结构体。

func (c *Configurator[T]) Watch(ctx context.Context, name string) error

MustWatch

与 Watch 类似,但出错时会 panic。

func (c *Configurator[T]) MustWatch(ctx context.Context, name string)

MustLoadAndWatch

便捷方法,调用 MustLoad 和 MustWatch。

func (c *Configurator[T]) MustLoadAndWatch(ctx context.Context, name string)

Get

返回当前配置结构体。

func (c *Configurator[T]) Get() T

GetPointer() *T

返回指向当前配置结构体的指针。

func (c *Configurator[T]) GetPointer() *T

OnChange

设置配置变化时调用的回调函数。

func (c *Configurator[T]) OnChange(fn func(updated T) error)

SetConverter

设置在 Load 操作期间使用的自定义转换函数。

func (c *Configurator[T]) SetConverter(converter func(data any, target *T) error)

SetLoadErrorHandler

设置 Load 操作失败时调用的错误处理函数。

func (c *Configurator[T]) SetLoadErrorHandler(errorFunc func(ctx context.Context, err error))

SetReuseTargetStruct

设置是否在更新时重用相同的目标结构体或创建新结构体。

func (c *Configurator[T]) SetReuseTargetStruct(reuse bool)

高级用法

监控特定配置键

// 只监控特定配置键
configurator := gcfg.NewConfiguratorWithAdapter[ServerConfig](cfg, "server")

使用默认值

// 创建带默认值的目标结构体
var targetConfig AppConfig
targetConfig.Name = "default-app" // 设置默认值

configurator := gcfg.NewConfiguratorWithAdapter(cfg, "", &targetConfig)

错误处理

Configurator 提供了灵活的错误处理机制:

configurator.SetLoadErrorHandler(func(ctx context.Context, err error) {
    // 处理加载错误
    log.Printf("配置加载失败: %v", err)
})

许可证

MIT License

LanceAdd and others added 8 commits December 25, 2025 15:03
- 实现了 Configurator 泛型结构体用于配置绑定
- 支持从配置文件或内容字符串创建配置器
- 提供配置加载、监听和管理功能
- 实现了线程安全的操作机制
- 支持自定义转换器和错误处理函数
- 提供配置变更回调功能
- 添加了完整的单元测试覆盖
- 包含详细的使用文档和示例代码
@LanceAdd LanceAdd changed the title feature(os/gprop): Add gprop module for type-safe configuration binding feat(gcfg): add Configurator for automatic configuration binding and watching Dec 26, 2025
@LanceAdd LanceAdd changed the title feat(gcfg): add Configurator for automatic configuration binding and watching feat(gcfg): add Configurator with automatic struct binding and config watching (like Spring Boot @ConfigurationProperties) Dec 29, 2025
- 实现了 GetPointer 方法用于获取当前配置结构体的指针
- 该方法是线程安全的,支持读操作但不应被修改
- 添加了相应的注释文档说明方法用途和安全性
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant