Skip to content

data-config 组件 ​

策划配表(数据配置)的读取与管理组件。支持本地文件、Redis、自定义数据源三种来源,支持热更新,并可通过 go-linq 做集合查询。

特性 ​

  • 数据源可插拔:本地文件 / Redis / 自定义实现
  • 文件格式可插拔:目前内置 JSON 解析器
  • 支持热更新(文件变更监听 / Redis 订阅)
  • 可自定义类型检测

安装 ​

bash
go get github.com/cherry-game/components/data-config@latest

注册组件 ​

go
import (
	"github.com/cherry-game/cherry"
	cherryDataConfig "github.com/cherry-game/components/data-config"
)

func main() {
	app := cherry.Configure("./config/profile.json", "game-1", false, cherry.Cluster)

	dataConfig := cherryDataConfig.New()
	dataConfig.Register(
		&DropList{},   // 注册实现了 IConfig 的结构体
		&DropOne{},
	)

	app.Register(dataConfig)
	app.Startup()
}

注意构造函数名

是 New() 而不是 NewComponent(),注册到框架用 app.Register(...) 而不是 cherry.RegisterComponent(...)(后者已不存在)。

配置 ​

配置节点为 data_config,缺失会导致进程 Fatal。

json
{
    "data_config": {
        "parser": "json",
        "data_source": "file",

        "file": {
            "file_path": "data/",
            "ext_name": ".json",
            "reload_time": 3000
        },

        "redis": {
            "address": "127.0.0.1:6379",
            "password": "",
            "db": 7,
            "prefix_key": "data_config",
            "subscribe_key": "data_config_change"
        }
    }
}
参数类型默认值说明
parserstring—解析器名,目前支持 json
data_sourcestring—数据源名:file / redis
file.file_pathstringdata/配表目录,相对 profile 文件所在目录
file.ext_namestring.json文件扩展名
file.reload_timeint3000重载扫描间隔(毫秒)
redis.addressstring—Redis 地址
redis.passwordstring—Redis 密码
redis.dbint—Redis 库号
redis.prefix_keystring—key 前缀,完整 key 为 <prefix_key>:<配置名>
redis.subscribe_keystring—变更订阅 key,为空会 panic

只有 data_source 指向的那一段会被实际使用,另一段可保留作为切换备用。

实现一张配表 ​

配表结构体需要实现 IConfig 接口:

go
type IConfig interface {
	Name() string  // 配置名,对应 data/<name>.json
	Init()
	OnLoad(maps any, reload bool) (int, error)
	OnAfterLoad(reload bool)
}

以 dropConfig.json 为例:

go
package demo

import (
	cerr "github.com/cherry-game/cherry/error"
	cherryMapStructure "github.com/cherry-game/cherry/extend/mapstructure"
)

type DropConfig struct {
	DropId  int32  `json:"dropId"`
	Quality int32  `json:"quality"`
}

type DropList struct {
	list []*DropConfig
}

// Name 对应 data/dropConfig.json
func (d *DropList) Name() string {
	return "dropConfig"
}

func (d *DropList) Init() {}

func (d *DropList) OnLoad(maps any, reload bool) (int, error) {
	list, ok := maps.([]any)
	if !ok {
		return 0, cerr.Error("maps convert to []interface{} error.")
	}

	// 热更新时必须先清空旧数据
	if reload {
		d.list = d.list[0:0]
	}

	for _, data := range list {
		var item DropConfig
		if cherryMapStructure.Decode(data, &item) == nil {
			d.list = append(d.list, &item)
		}
	}

	return len(list), nil
}

func (d *DropList) OnAfterLoad(reload bool) {
	// 可以在这里建索引,供业务快速查找
}

热更新要自己清空

OnLoad(maps, reload) 的 reload 为 true 表示这是一次热更新。此时必须自己清空旧数据(如 d.list = d.list[0:0]),否则新数据会追加到旧数据后面。

读取配表 ​

go
// 取整个配表对象,然后断言成自己的类型
comp := app.Find(cherryDataConfig.Name).(*cherryDataConfig.Component)
dropList := comp.GetIConfig("dropConfig").(*DropList)

// 取原始字节
data, ok := comp.GetBytes("dropConfig")

用 go-linq 查询 ​

配表实现里通常会把数据暴露成 slice,配合 go-linq 做条件查询:

go
import "github.com/ahmetb/go-linq/v3"

var results []DropConfig
linq.From(dropList.list).
	Where(func(i any) bool {
		return i.(*DropConfig).Quality >= 3
	}).
	Select(func(i any) any {
		return *i.(*DropConfig)
	}).
	ToSlice(&results)

扩展数据源与解析器 ​

两者都是注册表模式,可以替换:

go
// 注册自定义解析器(如 XML、CSV)
cherryDataConfig.RegisterParser(&MyParser{})

// 注册自定义数据源(如 MySQL、HTTP 接口)
cherryDataConfig.RegisterSource(&MySource{})

实现对应接口:

go
type IDataParser interface {
	TypeName() string
	Unmarshal(data []byte, v any) error
}

type IDataSource interface {
	Name() string
	Init(cfg IDataConfig)
}

然后在配置里把 parser 或 data_source 指向你注册的名字即可。

API ​

方法说明
New() *Component创建组件
Register(configs ...IConfig)注册配表结构体
GetIConfig(name string) IConfig按名字取配表对象
GetBytes(configName string) ([]byte, bool)取配表原始字节
GetParser() IDataParser当前解析器
GetDataSource() IDataSource当前数据源

包级注册表函数:RegisterParser、GetParser、RegisterSource、GetDataSource。

配表的完整可运行示例见 examples/test_data_config。