Apollo 技术文档Apollo 技术文档
指南
  • 架构概述
  • BigWorld 架构深度解析
  • BigWorld 进程架构与玩家生命周期
  • AOI九宫格系统详解
  • AOI广播与消息去重
  • Base 模块
  • Core 模块
  • Runtime 模块
  • Data 模块
  • Network 模块
  • /modules/actor.html
  • Game 模块
  • BigWorld 模块
服务器应用
API 参考
QA
GitHub
指南
  • 架构概述
  • BigWorld 架构深度解析
  • BigWorld 进程架构与玩家生命周期
  • AOI九宫格系统详解
  • AOI广播与消息去重
  • Base 模块
  • Core 模块
  • Runtime 模块
  • Data 模块
  • Network 模块
  • /modules/actor.html
  • Game 模块
  • BigWorld 模块
服务器应用
API 参考
QA
GitHub
  • 开始

    • 指南
    • 安装
    • 快速开始
  • 基础

    • 核心概念
    • 模块系统
    • 配置

配置系统

Apollo 提供灵活的配置管理,支持多种格式和热更新。

配置文件格式

支持 JSON、YAML、TOML 格式。

config.json

{
  "server": {
    "host": "0.0.0.0",
    "port": 8888
  },
  "database": {
    "host": "localhost",
    "port": 3306,
    "name": "apollo",
    "user": "root",
    "password": "123456"
  },
  "log": {
    "level": "info",
    "file": "logs/server.log"
  }
}

使用配置

加载配置

#include <apollo/core/config.hpp>

// 加载配置文件
auto& config = core::ConfigManager::instance();
config.load("config.json");

// 或从环境变量
config.loadFromEnv();

读取配置

// 读取简单值
int port = config.get<int>("server.port");
std::string host = config.get<std::string>("server.host");

// 读取嵌套值
std::string dbUser = config.get<std::string>("database.user");

// 带默认值
int timeout = config.get<int>("server.timeout", 30);

配置监听

// 监听配置变化
config.onChange("server.port", [](int newPort) {
    LOG_INFO("Config", "端口已更改为: {}", newPort);
});

热更新

配置文件修改后自动重新加载:

// 启用热更新
config.enableHotReload("config.json");

// 热更新回调
config.onReload([]() {
    LOG_INFO("Config", "配置已重新加载");
});

环境变量覆盖

环境变量可以覆盖配置文件中的值:

export APOLLO_SERVER_PORT=9999
export APOLLO_DATABASE_HOST=192.168.1.100
// 优先级:环境变量 > 命令行参数 > 配置文件
config.setOverrideStrategy(ConfigOverride::EnvFirst);

命令行参数

// 解析命令行参数
config.parseArgs(argc, argv);

// 支持:
// --server.port=8888
// --server.host=0.0.0.0
// -p 8888

配置验证

// 定义配置schema
config.defineSchema("server", {
    {"host", ConfigType::String, true},
    {"port", ConfigType::Int, true, [](const Variant& v) {
        return v.toInt() > 0 && v.toInt() < 65536;
    }}
});

// 验证配置
if (!config.validate()) {
    LOG_ERROR("Config", "配置验证失败");
}

下一步

查看 架构文档 了解更多。

在 GitHub 上编辑此页
最后更新: 3/20/26, 6:06 AM
贡献者: cuihairu
Prev
模块系统