Skip to content

配置源概述

Apq.Cfg 支持多种配置源,可以灵活组合使用。

默认层级

每种配置源都有默认层级,如果不指定 level 参数,将使用默认值:

配置源类型默认层级
Json, Ini, Xml, Yaml, Toml, Hcl, Properties0
Redis, Database100
Consul, Etcd, Nacos, Apollo, Zookeeper200
Vault300
.env, EnvironmentVariables400

配置源分类

本地配置源

从本地文件或环境读取配置:

配置源NuGet 包默认层级说明
JSONApq.Cfg (内置)0JSON 格式配置文件
YAMLApq.Cfg.Yaml0YAML 格式配置文件
XMLApq.Cfg.Xml0XML 格式配置文件
INIApq.Cfg.Ini0INI 格式配置文件
TOMLApq.Cfg.Toml0TOML 格式配置文件
HOCONApq.Cfg.Hcl0HOCON 格式配置文件
PropertiesApq.Cfg.Properties0Java Properties 格式配置文件
.env 文件Apq.Cfg.Env400.env 格式配置文件
环境变量Apq.Cfg (内置)400系统环境变量

数据存储配置源

从数据存储系统读取配置:

配置源NuGet 包默认层级说明
RedisApq.Cfg.Redis100Redis 键值存储
DatabaseApq.Cfg.Database100数据库配置源(支持多种数据库)

远程配置中心

从远程配置中心读取配置:

配置源NuGet 包默认层级说明
ConsulApq.Cfg.Consul200HashiCorp Consul
EtcdApq.Cfg.Etcd200Etcd 分布式键值存储
NacosApq.Cfg.Nacos200阿里巴巴 Nacos
ApolloApq.Cfg.Apollo200携程 Apollo 配置中心
ZookeeperApq.Cfg.Zookeeper200Apache Zookeeper
VaultApq.Cfg.Vault300HashiCorp Vault

配置源选择指南

开发环境

推荐使用本地文件配置:

csharp
var cfg = new CfgBuilder()
    .AddJsonFile("config.json")                                    // 使用默认层级 0
    .AddJsonFile("config.Development.json", level: 10, optional: true)
    .AddEnvironmentVariables(prefix: "APP_")                   // 使用默认层级 400
    .Build();

生产环境

推荐使用远程配置中心:

csharp
var cfg = new CfgBuilder()
    .AddJsonFile("config.json")                    // 使用默认层级 0
    .AddConsul(options => { ... })             // 使用默认层级 200
    .AddVault(options => { ... })              // 使用默认层级 300
    .Build();

混合部署

csharp
var cfg = new CfgBuilder()
    // 本地基础配置(使用默认层级 0)
    .AddJsonFile("config.json")
    // 环境特定配置
    .AddJsonFile($"config.{env}.json", level: 10, optional: true)
    // 远程配置(使用默认层级 200)
    .AddConsul(options => { ... })
    // 环境变量覆盖(使用默认层级 400)
    .AddEnvironmentVariables(prefix: "APP_")
    .Build();

配置源特性对比

特性JSONYAMLConsulRedisApollo
动态重载
分布式
版本控制
灰度发布
权限控制
审计日志

配置源优先级

使用 level 参数控制优先级,数值越大优先级越高:

csharp
var cfg = new CfgBuilder()
    .AddJsonFile("base.json", level: 0, writeable: false)           // 优先级 0(最低)
    .AddYamlFile("override.yaml", level: 1, writeable: false)       // 优先级 1
    .AddSource(new ConsulCfgSource(..., level: 10))             // 优先级 10
    .AddEnvironmentVariables(level: 20, prefix: "APP_")         // 优先级 20(最高)
    .Build();

下一步

选择您需要的配置源了解详细用法:

基于 MIT 许可发布