黄中银 3 дней назад
Родитель
Сommit
ebc95eda1f

+ 22 - 2
Samples/Apq.Cfg.Samples/Apq.Cfg.Samples.csproj

@@ -1,23 +1,43 @@
 <Project Sdk="Microsoft.NET.Sdk">
 
   <ItemGroup>
+    <!-- 核心库 -->
     <ProjectReference Include="..\..\Apq.Cfg\Apq.Cfg.csproj" />
+    
+    <!-- 文件格式扩展 -->
     <ProjectReference Include="..\..\Apq.Cfg.Ini\Apq.Cfg.Ini.csproj" />
     <ProjectReference Include="..\..\Apq.Cfg.Xml\Apq.Cfg.Xml.csproj" />
     <ProjectReference Include="..\..\Apq.Cfg.Yaml\Apq.Cfg.Yaml.csproj" />
     <ProjectReference Include="..\..\Apq.Cfg.Toml\Apq.Cfg.Toml.csproj" />
+    
+    <!-- 数据存储扩展 -->
+    <ProjectReference Include="..\..\Apq.Cfg.Redis\Apq.Cfg.Redis.csproj" />
+    <ProjectReference Include="..\..\Apq.Cfg.Database\Apq.Cfg.Database.csproj" />
+    
+    <!-- 远程配置中心 -->
+    <ProjectReference Include="..\..\Apq.Cfg.Consul\Apq.Cfg.Consul.csproj" />
+    <ProjectReference Include="..\..\Apq.Cfg.Etcd\Apq.Cfg.Etcd.csproj" />
+    <ProjectReference Include="..\..\Apq.Cfg.Nacos\Apq.Cfg.Nacos.csproj" />
+    <ProjectReference Include="..\..\Apq.Cfg.Apollo\Apq.Cfg.Apollo.csproj" />
+    <ProjectReference Include="..\..\Apq.Cfg.Zookeeper\Apq.Cfg.Zookeeper.csproj" />
+    <ProjectReference Include="..\..\Apq.Cfg.Vault\Apq.Cfg.Vault.csproj" />
+    
+    <!-- 源生成器 - 同时作为 Analyzer 和程序集引用 -->
+    <ProjectReference Include="..\..\Apq.Cfg.SourceGenerator\Apq.Cfg.SourceGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="true" />
   </ItemGroup>
 
   <ItemGroup>
-    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.1" />
+    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.1" />
   </ItemGroup>
 
   <PropertyGroup>
     <OutputType>Exe</OutputType>
-    <TargetFramework>net8.0</TargetFramework>
+    <TargetFrameworks>net8.0;net9.0</TargetFrameworks>
     <ImplicitUsings>enable</ImplicitUsings>
     <Nullable>enable</Nullable>
     <IsPackable>false</IsPackable>
+    <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
+    <CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GeneratedFiles</CompilerGeneratedFilesOutputPath>
   </PropertyGroup>
 
 </Project>

+ 257 - 0
Samples/Apq.Cfg.Samples/Demos/ApolloDemo.cs

@@ -0,0 +1,257 @@
+using Apq.Cfg;
+using Apq.Cfg.Apollo;
+
+namespace Apq.Cfg.Samples.Demos;
+
+/// <summary>
+/// 示例 14: Apollo 配置中心
+/// 演示如何使用 Apollo 作为配置源
+/// </summary>
+public static class ApolloDemo
+{
+    public static async Task RunAsync(string baseDir)
+    {
+        Console.WriteLine("═══════════════════════════════════════════════════════════════");
+        Console.WriteLine("示例 14: Apollo 配置中心");
+        Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
+
+        // 注意:此示例需要运行中的 Apollo 服务
+        // Apollo 部署较复杂,建议参考官方文档:https://www.apolloconfig.com/
+        
+        Console.WriteLine("【Apollo 配置源说明】");
+        Console.WriteLine("Apollo 是携程开源的分布式配置中心,支持配置的集中管理和动态推送。");
+        Console.WriteLine("Apq.Cfg.Apollo 支持从 Apollo 配置中心读取配置。\n");
+
+        // 示例 1: 基本配置
+        Console.WriteLine("--- 示例 14.1: 基本配置 ---");
+        ShowBasicConfiguration();
+
+        // 示例 2: 多命名空间
+        Console.WriteLine("\n--- 示例 14.2: 多命名空间 ---");
+        ShowMultiNamespaceConfiguration();
+
+        // 示例 3: 集群配置
+        Console.WriteLine("\n--- 示例 14.3: 集群配置 ---");
+        ShowClusterConfiguration();
+
+        // 示例 4: 访问密钥
+        Console.WriteLine("\n--- 示例 14.4: 访问密钥 ---");
+        ShowSecretConfiguration();
+
+        // 示例 5: 不同数据格式
+        Console.WriteLine("\n--- 示例 14.5: 不同数据格式 ---");
+        ShowDataFormatConfiguration();
+
+        // 示例 6: 热重载
+        Console.WriteLine("\n--- 示例 14.6: 热重载 ---");
+        ShowHotReloadConfiguration();
+
+        // 示例 7: 实际连接测试
+        Console.WriteLine("\n--- 示例 14.7: 连接测试 ---");
+        await TestConnectionAsync();
+
+        Console.WriteLine("\n示例 14 完成\n");
+    }
+
+    private static void ShowBasicConfiguration()
+    {
+        Console.WriteLine("基本配置代码示例:");
+        Console.WriteLine(@"
+// 使用 Action 配置
+var cfg = new CfgBuilder()
+    .AddApollo(options =>
+    {
+        options.AppId = ""myapp"";                     // 应用 ID
+        options.MetaServer = ""http://localhost:8080""; // Meta Server 地址
+        options.Namespaces = new[] { ""application"" }; // 命名空间
+    }, level: 0)
+    .Build();
+
+// 或使用简化方法
+var cfg2 = new CfgBuilder()
+    .AddApollo(""myapp"", metaServer: ""http://localhost:8080"")
+    .Build();
+
+// 读取配置
+var host = cfg.Get(""Database:Host"");
+");
+    }
+
+    private static void ShowMultiNamespaceConfiguration()
+    {
+        Console.WriteLine("多命名空间配置:");
+        Console.WriteLine(@"
+// Apollo 支持多个命名空间,可以实现配置的模块化管理
+var cfg = new CfgBuilder()
+    .AddApollo(options =>
+    {
+        options.AppId = ""myapp"";
+        options.MetaServer = ""http://localhost:8080"";
+        options.Namespaces = new[]
+        {
+            ""application"",      // 默认命名空间
+            ""database"",         // 数据库配置
+            ""redis"",            // Redis 配置
+            ""common.shared""     // 公共配置(关联命名空间)
+        };
+    }, level: 0)
+    .Build();
+
+// 或使用简化方法
+var cfg2 = new CfgBuilder()
+    .AddApollo(
+        ""myapp"",
+        metaServer: ""http://localhost:8080"",
+        namespaces: new[] { ""application"", ""database"" })
+    .Build();
+");
+    }
+
+    private static void ShowClusterConfiguration()
+    {
+        Console.WriteLine("集群配置:");
+        Console.WriteLine(@"
+// Apollo 支持集群,可以为不同机房/环境配置不同的值
+var cfg = new CfgBuilder()
+    .AddApollo(options =>
+    {
+        options.AppId = ""myapp"";
+        options.MetaServer = ""http://apollo-meta.example.com:8080"";
+        options.Cluster = ""SHAJQ"";  // 上海机房集群
+        options.Namespaces = new[] { ""application"" };
+    }, level: 0)
+    .Build();
+
+// 北京机房配置
+var cfgBJ = new CfgBuilder()
+    .AddApollo(options =>
+    {
+        options.AppId = ""myapp"";
+        options.MetaServer = ""http://apollo-meta-bj.example.com:8080"";
+        options.Cluster = ""BJZJY"";  // 北京机房集群
+        options.Namespaces = new[] { ""application"" };
+    }, level: 0)
+    .Build();
+");
+    }
+
+    private static void ShowSecretConfiguration()
+    {
+        Console.WriteLine("访问密钥配置:");
+        Console.WriteLine(@"
+// 当 Apollo 启用访问控制时,需要配置 Secret
+var cfg = new CfgBuilder()
+    .AddApollo(options =>
+    {
+        options.AppId = ""myapp"";
+        options.MetaServer = ""http://localhost:8080"";
+        options.Namespaces = new[] { ""application"" };
+        options.Secret = ""your-app-secret"";  // 访问密钥
+        options.ConnectTimeout = TimeSpan.FromSeconds(10);
+    }, level: 0)
+    .Build();
+");
+    }
+
+    private static void ShowDataFormatConfiguration()
+    {
+        Console.WriteLine("不同数据格式配置:");
+        Console.WriteLine(@"
+// 1. Properties 格式(默认)
+var cfgProps = new CfgBuilder()
+    .AddApollo(options =>
+    {
+        options.AppId = ""myapp"";
+        options.MetaServer = ""http://localhost:8080"";
+        options.Namespaces = new[] { ""application"" };
+        options.DataFormat = ApolloDataFormat.Properties;
+    }, level: 0)
+    .Build();
+
+// 2. JSON 格式(需要在 Apollo 中创建 .json 后缀的命名空间)
+var cfgJson = new CfgBuilder()
+    .AddApollo(options =>
+    {
+        options.AppId = ""myapp"";
+        options.MetaServer = ""http://localhost:8080"";
+        options.Namespaces = new[] { ""application.json"" };
+        options.DataFormat = ApolloDataFormat.Json;
+    }, level: 0)
+    .Build();
+
+// 3. YAML 格式(需要在 Apollo 中创建 .yaml 后缀的命名空间)
+var cfgYaml = new CfgBuilder()
+    .AddApollo(options =>
+    {
+        options.AppId = ""myapp"";
+        options.MetaServer = ""http://localhost:8080"";
+        options.Namespaces = new[] { ""application.yaml"" };
+        options.DataFormat = ApolloDataFormat.Yaml;
+    }, level: 0)
+    .Build();
+");
+    }
+
+    private static void ShowHotReloadConfiguration()
+    {
+        Console.WriteLine("热重载配置:");
+        Console.WriteLine(@"
+var cfg = new CfgBuilder()
+    .AddApollo(options =>
+    {
+        options.AppId = ""myapp"";
+        options.MetaServer = ""http://localhost:8080"";
+        options.Namespaces = new[] { ""application"" };
+        options.EnableHotReload = true;                    // 启用热重载(默认 true)
+        options.LongPollingTimeout = TimeSpan.FromSeconds(90); // 长轮询超时
+    }, level: 0)
+    .Build();
+
+// 订阅配置变更
+cfg.ConfigChanges.Subscribe(change =>
+{
+    Console.WriteLine($""配置变更: {change.Key}"");
+    Console.WriteLine($""  旧值: {change.OldValue}"");
+    Console.WriteLine($""  新值: {change.NewValue}"");
+});
+
+// 注意:Apollo 是只读配置源,不支持通过 API 写入配置
+// 配置修改需要通过 Apollo 管理界面进行
+");
+    }
+
+    private static async Task TestConnectionAsync()
+    {
+        Console.WriteLine("尝试连接本地 Apollo...");
+        
+        try
+        {
+            var cfg = new CfgBuilder()
+                .AddApollo(options =>
+                {
+                    options.AppId = "apq-cfg-demo";
+                    options.MetaServer = "http://localhost:8080";
+                    options.Namespaces = new[] { "application" };
+                    options.ConnectTimeout = TimeSpan.FromSeconds(3);
+                }, level: 0)
+                .Build();
+
+            // 尝试读取配置
+            var testValue = cfg.Get("test");
+            Console.WriteLine($"✓ 连接成功!test 键的值: {testValue ?? "(空)"}");
+            
+            // 显示所有键
+            var keys = cfg.GetChildKeys();
+            Console.WriteLine($"  配置键数量: {keys.Count()}");
+        }
+        catch (Exception ex)
+        {
+            Console.WriteLine($"✗ 连接失败: {ex.Message}");
+            Console.WriteLine("  提示: Apollo 部署较复杂,请参考官方文档");
+            Console.WriteLine("  官方文档: https://www.apolloconfig.com/");
+            Console.WriteLine("  Quick Start: https://www.apolloconfig.com/#/zh/deployment/quick-start");
+        }
+        
+        await Task.CompletedTask;
+    }
+}

+ 91 - 0
Samples/Apq.Cfg.Samples/Demos/BasicUsageDemo.cs

@@ -0,0 +1,91 @@
+namespace Apq.Cfg.Samples.Demos;
+
+/// <summary>
+/// 示例 1: 基础用法 - JSON 配置与层级覆盖
+/// </summary>
+public static class BasicUsageDemo
+{
+    public static async Task RunAsync(string baseDir)
+    {
+        Console.WriteLine("═══════════════════════════════════════════════════════════════");
+        Console.WriteLine("示例 1: 基础用法 - JSON 配置与层级覆盖");
+        Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
+
+        var configPath = Path.Combine(baseDir, "config.json");
+        var localConfigPath = Path.Combine(baseDir, "config.local.json");
+
+        // 创建基础配置
+        File.WriteAllText(configPath, """
+        {
+            "App": {
+                "Name": "MyApp",
+                "Version": "1.0.0",
+                "Debug": false
+            },
+            "Database": {
+                "Host": "localhost",
+                "Port": 3306,
+                "Name": "mydb"
+            }
+        }
+        """);
+
+        // 创建本地覆盖配置(高优先级)
+        File.WriteAllText(localConfigPath, """
+        {
+            "App": {
+                "Debug": true
+            },
+            "Database": {
+                "Host": "192.168.1.100"
+            }
+        }
+        """);
+
+        // 构建配置:level 越大优先级越高
+        // 注意:环境变量不可写,所以 isPrimaryWriter 设置在 JSON 配置源上
+        var cfg = new CfgBuilder()
+            .AddJson(configPath, level: 0, writeable: false)
+            .AddJson(localConfigPath, level: 1, writeable: true, isPrimaryWriter: true)
+            .AddEnvironmentVariables(level: 2, prefix: "MYAPP_")
+            .Build();
+
+        // 读取配置
+        Console.WriteLine("1.1 读取配置值:");
+        Console.WriteLine($"    App:Name = {cfg.Get("App:Name")}");
+        Console.WriteLine($"    App:Version = {cfg.Get("App:Version")}");
+        Console.WriteLine($"    App:Debug = {cfg.Get("App:Debug")} (被本地配置覆盖为 true)");
+        Console.WriteLine($"    Database:Host = {cfg.Get("Database:Host")} (被本地配置覆盖)");
+        Console.WriteLine($"    Database:Port = {cfg.Get("Database:Port")}");
+
+        // 检查配置是否存在
+        Console.WriteLine("\n1.2 检查配置是否存在:");
+        Console.WriteLine($"    Exists(App:Name) = {cfg.Exists("App:Name")}");
+        Console.WriteLine($"    Exists(NotExist:Key) = {cfg.Exists("NotExist:Key")}");
+
+        // 修改配置(写入到 isPrimaryWriter 的配置源,需要指定 targetLevel)
+        Console.WriteLine("\n1.3 修改配置:");
+        cfg.Set("App:LastRun", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), targetLevel: 1);
+        await cfg.SaveAsync(targetLevel: 1);
+        Console.WriteLine($"    已设置 App:LastRun = {cfg.Get("App:LastRun")}");
+
+        // 删除配置
+        Console.WriteLine("\n1.4 删除配置:");
+        cfg.Set("App:TempKey", "临时值", targetLevel: 1);
+        Console.WriteLine($"    设置 App:TempKey = {cfg.Get("App:TempKey")}");
+        cfg.Remove("App:TempKey", targetLevel: 1);
+        await cfg.SaveAsync(targetLevel: 1);
+        Console.WriteLine($"    删除后 App:TempKey = {cfg.Get("App:TempKey") ?? "(null)"}");
+
+        // 转换为 Microsoft.Extensions.Configuration
+        Console.WriteLine("\n1.5 转换为 IConfigurationRoot:");
+        var msConfig = cfg.ToMicrosoftConfiguration();
+        Console.WriteLine($"    msConfig[\"App:Name\"] = {msConfig["App:Name"]}");
+
+        cfg.Dispose();
+        File.Delete(configPath);
+        File.Delete(localConfigPath);
+
+        Console.WriteLine("\n[示例 1 完成]\n");
+    }
+}

+ 70 - 0
Samples/Apq.Cfg.Samples/Demos/BatchOperationsDemo.cs

@@ -0,0 +1,70 @@
+namespace Apq.Cfg.Samples.Demos;
+
+/// <summary>
+/// 示例 4: 批量操作 - GetMany / SetMany
+/// </summary>
+public static class BatchOperationsDemo
+{
+    public static async Task RunAsync(string baseDir)
+    {
+        Console.WriteLine("═══════════════════════════════════════════════════════════════");
+        Console.WriteLine("示例 4: 批量操作 - GetMany / SetMany");
+        Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
+
+        var configPath = Path.Combine(baseDir, "batch-demo.json");
+        File.WriteAllText(configPath, """
+        {
+            "Settings": {
+                "Theme": "dark",
+                "Language": "zh-CN",
+                "FontSize": "14",
+                "AutoSave": "true"
+            }
+        }
+        """);
+
+        using var cfg = new CfgBuilder()
+            .AddJson(configPath, level: 0, writeable: true, isPrimaryWriter: true)
+            .Build();
+
+        // 批量获取
+        Console.WriteLine("4.1 批量获取 (GetMany):");
+        var keys = new[] { "Settings:Theme", "Settings:Language", "Settings:FontSize" };
+        var values = cfg.GetMany(keys);
+        foreach (var kv in values)
+        {
+            Console.WriteLine($"    {kv.Key} = {kv.Value}");
+        }
+
+        // 批量获取并转换类型
+        Console.WriteLine("\n4.2 批量获取并转换类型 (GetMany<T>):");
+        var intKeys = new[] { "Settings:FontSize" };
+        var intValues = cfg.GetMany<int>(intKeys);
+        foreach (var kv in intValues)
+        {
+            Console.WriteLine($"    {kv.Key} = {kv.Value} (int)");
+        }
+
+        // 批量设置
+        Console.WriteLine("\n4.3 批量设置 (SetMany):");
+        var newValues = new Dictionary<string, string?>
+        {
+            ["Settings:Theme"] = "light",
+            ["Settings:FontSize"] = "16",
+            ["Settings:NewOption"] = "enabled"
+        };
+        cfg.SetMany(newValues);
+        await cfg.SaveAsync();
+
+        Console.WriteLine("    批量设置后的值:");
+        var updatedValues = cfg.GetMany(new[] { "Settings:Theme", "Settings:FontSize", "Settings:NewOption" });
+        foreach (var kv in updatedValues)
+        {
+            Console.WriteLine($"    {kv.Key} = {kv.Value}");
+        }
+
+        File.Delete(configPath);
+
+        Console.WriteLine("\n[示例 4 完成]\n");
+    }
+}

+ 75 - 0
Samples/Apq.Cfg.Samples/Demos/ConfigSectionDemo.cs

@@ -0,0 +1,75 @@
+namespace Apq.Cfg.Samples.Demos;
+
+/// <summary>
+/// 示例 3: 配置节 (GetSection) 与子键枚举
+/// </summary>
+public static class ConfigSectionDemo
+{
+    public static async Task RunAsync(string baseDir)
+    {
+        Console.WriteLine("═══════════════════════════════════════════════════════════════");
+        Console.WriteLine("示例 3: 配置节 (GetSection) 与子键枚举");
+        Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
+
+        var configPath = Path.Combine(baseDir, "section-demo.json");
+        File.WriteAllText(configPath, """
+        {
+            "Database": {
+                "Primary": {
+                    "Host": "primary.db.local",
+                    "Port": 3306,
+                    "Username": "admin"
+                },
+                "Replica": {
+                    "Host": "replica.db.local",
+                    "Port": 3307,
+                    "Username": "reader"
+                }
+            },
+            "Cache": {
+                "Redis": {
+                    "Host": "redis.local",
+                    "Port": 6379
+                }
+            }
+        }
+        """);
+
+        using var cfg = new CfgBuilder()
+            .AddJson(configPath, level: 0, writeable: true, isPrimaryWriter: true)
+            .Build();
+
+        // 获取配置节
+        Console.WriteLine("3.1 使用 GetSection 简化嵌套访问:");
+        var dbSection = cfg.GetSection("Database");
+        var primarySection = dbSection.GetSection("Primary");
+
+        Console.WriteLine($"    Database:Primary:Host = {primarySection.Get("Host")}");
+        Console.WriteLine($"    Database:Primary:Port = {primarySection.Get<int>("Port")}");
+
+        // 枚举子键
+        Console.WriteLine("\n3.2 枚举配置节的子键:");
+        Console.WriteLine("    Database 的子键:");
+        foreach (var key in dbSection.GetChildKeys())
+        {
+            Console.WriteLine($"      - {key}");
+        }
+
+        Console.WriteLine("\n    顶级配置键:");
+        foreach (var key in cfg.GetChildKeys())
+        {
+            Console.WriteLine($"      - {key}");
+        }
+
+        // 通过配置节修改值
+        Console.WriteLine("\n3.3 通过配置节修改值:");
+        var replicaSection = dbSection.GetSection("Replica");
+        replicaSection.Set("Port", "3308");
+        await cfg.SaveAsync();
+        Console.WriteLine($"    修改后 Database:Replica:Port = {replicaSection.Get("Port")}");
+
+        File.Delete(configPath);
+
+        Console.WriteLine("\n[示例 3 完成]\n");
+    }
+}

+ 204 - 0
Samples/Apq.Cfg.Samples/Demos/ConsulDemo.cs

@@ -0,0 +1,204 @@
+using Apq.Cfg;
+using Apq.Cfg.Consul;
+
+namespace Apq.Cfg.Samples.Demos;
+
+/// <summary>
+/// 示例 11: Consul 配置中心
+/// 演示如何使用 Consul 作为配置源
+/// </summary>
+public static class ConsulDemo
+{
+    public static async Task RunAsync(string baseDir)
+    {
+        Console.WriteLine("═══════════════════════════════════════════════════════════════");
+        Console.WriteLine("示例 11: Consul 配置中心");
+        Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
+
+        // 注意:此示例需要运行中的 Consul 服务
+        // 可以使用 Docker 快速启动:docker run -d -p 8500:8500 consul
+        
+        Console.WriteLine("【Consul 配置源说明】");
+        Console.WriteLine("Consul 是 HashiCorp 开发的服务发现和配置管理工具。");
+        Console.WriteLine("Apq.Cfg.Consul 支持从 Consul KV 存储读取配置。\n");
+
+        // 示例 1: 基本配置
+        Console.WriteLine("--- 示例 11.1: 基本配置 ---");
+        ShowBasicConfiguration();
+
+        // 示例 2: 带认证的配置
+        Console.WriteLine("\n--- 示例 11.2: 带 ACL Token 认证 ---");
+        ShowAuthConfiguration();
+
+        // 示例 3: 监听配置变更
+        Console.WriteLine("\n--- 示例 11.3: 监听配置变更 ---");
+        ShowWatchConfiguration();
+
+        // 示例 4: 多数据中心
+        Console.WriteLine("\n--- 示例 11.4: 多数据中心配置 ---");
+        ShowMultiDatacenterConfiguration();
+
+        // 示例 5: 不同数据格式
+        Console.WriteLine("\n--- 示例 11.5: 不同数据格式 ---");
+        ShowDataFormatConfiguration();
+
+        // 示例 6: 实际连接测试(如果 Consul 可用)
+        Console.WriteLine("\n--- 示例 11.6: 连接测试 ---");
+        await TestConnectionAsync();
+
+        Console.WriteLine("\n示例 11 完成\n");
+    }
+
+    private static void ShowBasicConfiguration()
+    {
+        Console.WriteLine("基本配置代码示例:");
+        Console.WriteLine(@"
+var cfg = new CfgBuilder()
+    .AddConsul(options =>
+    {
+        options.Address = ""http://localhost:8500"";  // Consul 地址
+        options.KeyPrefix = ""myapp/config/"";        // KV 前缀
+    }, level: 0)
+    .Build();
+
+// 或使用简化方法
+var cfg2 = new CfgBuilder()
+    .AddConsul(""http://localhost:8500"", keyPrefix: ""myapp/config/"")
+    .Build();
+
+// 读取配置(假设 Consul 中有 myapp/config/Database/Host)
+var host = cfg.Get(""Database:Host"");
+");
+    }
+
+    private static void ShowAuthConfiguration()
+    {
+        Console.WriteLine("带 ACL Token 认证的配置:");
+        Console.WriteLine(@"
+var cfg = new CfgBuilder()
+    .AddConsul(options =>
+    {
+        options.Address = ""http://localhost:8500"";
+        options.KeyPrefix = ""myapp/config/"";
+        options.Token = ""your-acl-token"";           // ACL Token
+        options.Datacenter = ""dc1"";                 // 数据中心
+    }, level: 0)
+    .Build();
+");
+    }
+
+    private static void ShowWatchConfiguration()
+    {
+        Console.WriteLine("监听配置变更:");
+        Console.WriteLine(@"
+var cfg = new CfgBuilder()
+    .AddConsul(options =>
+    {
+        options.Address = ""http://localhost:8500"";
+        options.KeyPrefix = ""myapp/config/"";
+        options.EnableHotReload = true;              // 启用热重载(默认 true)
+        options.WaitTime = TimeSpan.FromMinutes(5);  // Blocking Query 等待时间
+    }, level: 0)
+    .Build();
+
+// 订阅配置变更
+cfg.ConfigChanges.Subscribe(change =>
+{
+    Console.WriteLine($""配置变更: {change.Key} = {change.NewValue}"");
+});
+");
+    }
+
+    private static void ShowMultiDatacenterConfiguration()
+    {
+        Console.WriteLine("多数据中心配置:");
+        Console.WriteLine(@"
+// 可以从多个数据中心加载配置,实现配置的层级覆盖
+var cfg = new CfgBuilder()
+    .AddConsul(options =>
+    {
+        options.Address = ""http://consul-dc1:8500"";
+        options.KeyPrefix = ""shared/config/"";
+        options.Datacenter = ""dc1"";
+    }, level: 0)  // 基础配置
+    .AddConsul(options =>
+    {
+        options.Address = ""http://consul-dc2:8500"";
+        options.KeyPrefix = ""myapp/config/"";
+        options.Datacenter = ""dc2"";
+    }, level: 1)  // 应用特定配置(覆盖基础配置)
+    .Build();
+");
+    }
+
+    private static void ShowDataFormatConfiguration()
+    {
+        Console.WriteLine("不同数据格式配置:");
+        Console.WriteLine(@"
+// 1. KeyValue 格式(默认)- 每个 KV 键对应一个配置项
+var cfg1 = new CfgBuilder()
+    .AddConsul(options =>
+    {
+        options.Address = ""http://localhost:8500"";
+        options.KeyPrefix = ""myapp/config/"";
+        options.DataFormat = ConsulDataFormat.KeyValue;
+    }, level: 0)
+    .Build();
+
+// 2. JSON 格式 - 单个 key 存储 JSON 配置
+var cfg2 = new CfgBuilder()
+    .AddConsul(options =>
+    {
+        options.Address = ""http://localhost:8500"";
+        options.KeyPrefix = ""myapp/"";
+        options.DataFormat = ConsulDataFormat.Json;
+        options.SingleKey = ""config.json"";  // 读取 myapp/config.json
+    }, level: 0)
+    .Build();
+
+// 3. YAML 格式 - 单个 key 存储 YAML 配置
+var cfg3 = new CfgBuilder()
+    .AddConsul(options =>
+    {
+        options.Address = ""http://localhost:8500"";
+        options.KeyPrefix = ""myapp/"";
+        options.DataFormat = ConsulDataFormat.Yaml;
+        options.SingleKey = ""config.yaml"";
+    }, level: 0)
+    .Build();
+");
+    }
+
+    private static async Task TestConnectionAsync()
+    {
+        Console.WriteLine("尝试连接本地 Consul...");
+        
+        try
+        {
+            var cfg = new CfgBuilder()
+                .AddConsul(options =>
+                {
+                    options.Address = "http://localhost:8500";
+                    options.KeyPrefix = "apq-cfg-demo/";
+                    options.ConnectTimeout = TimeSpan.FromSeconds(3);
+                }, level: 0)
+                .Build();
+
+            // 尝试读取配置
+            var testValue = cfg.Get("test");
+            Console.WriteLine($"✓ 连接成功!test 键的值: {testValue ?? "(空)"}");
+            
+            // 显示所有键
+            var keys = cfg.GetChildKeys();
+            Console.WriteLine($"  配置键数量: {keys.Count()}");
+        }
+        catch (Exception ex)
+        {
+            Console.WriteLine($"✗ 连接失败: {ex.Message}");
+            Console.WriteLine("  提示: 请确保 Consul 服务正在运行");
+            Console.WriteLine("  快速启动: docker run -d -p 8500:8500 consul");
+        }
+        
+        await Task.CompletedTask;
+    }
+}

+ 115 - 0
Samples/Apq.Cfg.Samples/Demos/DatabaseDemo.cs

@@ -0,0 +1,115 @@
+using Apq.Cfg.Database;
+
+namespace Apq.Cfg.Samples.Demos;
+
+/// <summary>
+/// 示例 10: 数据库配置源
+/// 注意:需要运行数据库服务才能执行此示例
+/// </summary>
+public static class DatabaseDemo
+{
+    public static async Task RunAsync(string baseDir)
+    {
+        Console.WriteLine("═══════════════════════════════════════════════════════════════");
+        Console.WriteLine("示例 10: 数据库配置源");
+        Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
+
+        Console.WriteLine("注意:此示例需要运行数据库服务\n");
+
+        // 使用 SQLite 作为示例(无需额外服务)
+        var dbPath = Path.Combine(baseDir, "config.db");
+
+        try
+        {
+            Console.WriteLine("10.1 使用 SQLite 数据库配置源:");
+            Console.WriteLine($"    数据库文件: {dbPath}");
+
+            var cfg = new CfgBuilder()
+                .AddDatabase(options =>
+                {
+                    options.Provider = "SQLite";
+                    options.ConnectionString = $"Data Source={dbPath}";
+                    options.Table = "AppConfig";
+                    options.KeyColumn = "ConfigKey";
+                    options.ValueColumn = "ConfigValue";
+                }, level: 0, isPrimaryWriter: true)
+                .Build();
+
+            Console.WriteLine("    已连接到 SQLite 数据库");
+
+            // 写入配置
+            Console.WriteLine("\n10.2 写入配置到数据库:");
+            cfg.Set("App:Name", "DatabaseApp");
+            cfg.Set("App:Version", "1.0.0");
+            cfg.Set("Database:MaxConnections", "100");
+            await cfg.SaveAsync();
+            Console.WriteLine("    已写入 3 个配置项");
+
+            // 读取配置
+            Console.WriteLine("\n10.3 从数据库读取配置:");
+            Console.WriteLine($"    App:Name = {cfg.Get("App:Name")}");
+            Console.WriteLine($"    App:Version = {cfg.Get("App:Version")}");
+            Console.WriteLine($"    Database:MaxConnections = {cfg.Get<int>("Database:MaxConnections")}");
+
+            // 修改配置
+            Console.WriteLine("\n10.4 修改配置:");
+            cfg.Set("App:Version", "2.0.0");
+            await cfg.SaveAsync();
+            Console.WriteLine($"    修改后 App:Version = {cfg.Get("App:Version")}");
+
+            // 删除配置
+            Console.WriteLine("\n10.5 删除配置:");
+            cfg.Remove("App:Name");
+            cfg.Remove("App:Version");
+            cfg.Remove("Database:MaxConnections");
+            await cfg.SaveAsync();
+            Console.WriteLine("    已清理测试配置");
+
+            cfg.Dispose();
+
+            // 等待数据库连接完全释放
+            await Task.Delay(100);
+            GC.Collect();
+            GC.WaitForPendingFinalizers();
+
+            // 清理数据库文件
+            try
+            {
+                if (File.Exists(dbPath))
+                    File.Delete(dbPath);
+            }
+            catch
+            {
+                // 忽略删除失败
+            }
+
+            Console.WriteLine("\n10.6 其他数据库支持:");
+            Console.WriteLine("    - SqlServer: Provider=\"SqlServer\"");
+            Console.WriteLine("    - MySQL: Provider=\"MySql\"");
+            Console.WriteLine("    - PostgreSQL: Provider=\"PostgreSQL\"");
+            Console.WriteLine("    - Oracle: Provider=\"Oracle\"");
+
+            Console.WriteLine("\n[示例 10 完成]\n");
+        }
+        catch (Exception ex)
+        {
+            Console.WriteLine($"    [跳过] 数据库服务不可用: {ex.Message}");
+            
+            // 等待连接释放后再删除
+            await Task.Delay(100);
+            GC.Collect();
+            GC.WaitForPendingFinalizers();
+            
+            try
+            {
+                if (File.Exists(dbPath))
+                    File.Delete(dbPath);
+            }
+            catch
+            {
+                // 忽略删除失败
+            }
+            Console.WriteLine("\n[示例 10 跳过]\n");
+        }
+    }
+}

+ 72 - 0
Samples/Apq.Cfg.Samples/Demos/DependencyInjectionDemo.cs

@@ -0,0 +1,72 @@
+using Apq.Cfg.Samples.Models;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Options;
+
+namespace Apq.Cfg.Samples.Demos;
+
+/// <summary>
+/// 示例 7: 依赖注入集成
+/// </summary>
+public static class DependencyInjectionDemo
+{
+    public static async Task RunAsync(string baseDir)
+    {
+        Console.WriteLine("═══════════════════════════════════════════════════════════════");
+        Console.WriteLine("示例 7: 依赖注入集成");
+        Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
+
+        var configPath = Path.Combine(baseDir, "di-demo.json");
+        File.WriteAllText(configPath, """
+        {
+            "Database": {
+                "Host": "db.example.com",
+                "Port": "5432",
+                "Name": "production"
+            },
+            "Logging": {
+                "Level": "Information",
+                "EnableConsole": "true"
+            }
+        }
+        """);
+
+        // 配置服务容器
+        var services = new ServiceCollection();
+
+        // 方式1: 使用 AddApqCfg 注册配置
+        Console.WriteLine("7.1 注册 Apq.Cfg 到 DI 容器:");
+        services.AddApqCfg(cfg => cfg
+            .AddJson(configPath, level: 0, writeable: true, isPrimaryWriter: true));
+        Console.WriteLine("    已注册 ICfgRoot 和 IConfigurationRoot");
+
+        // 方式2: 绑定强类型配置
+        Console.WriteLine("\n7.2 绑定强类型配置:");
+        services.ConfigureApqCfg<DatabaseOptions>("Database");
+        services.ConfigureApqCfg<LoggingOptions>("Logging");
+        Console.WriteLine("    已绑定 DatabaseOptions 和 LoggingOptions");
+
+        // 构建服务提供者
+        var provider = services.BuildServiceProvider();
+
+        // 获取服务
+        Console.WriteLine("\n7.3 从 DI 容器获取服务:");
+        var cfgRoot = provider.GetRequiredService<ICfgRoot>();
+        var msConfig = provider.GetRequiredService<IConfigurationRoot>();
+        var dbOptions = provider.GetRequiredService<IOptions<DatabaseOptions>>().Value;
+        var logOptions = provider.GetRequiredService<IOptions<LoggingOptions>>().Value;
+
+        Console.WriteLine($"    ICfgRoot: Database:Host = {cfgRoot.Get("Database:Host")}");
+        Console.WriteLine($"    IConfigurationRoot: Database:Host = {msConfig["Database:Host"]}");
+        Console.WriteLine($"    DatabaseOptions: Host={dbOptions.Host}, Port={dbOptions.Port}, Name={dbOptions.Name}");
+        Console.WriteLine($"    LoggingOptions: Level={logOptions.Level}, EnableConsole={logOptions.EnableConsole}");
+
+        // 清理
+        if (provider is IDisposable disposable)
+            disposable.Dispose();
+        File.Delete(configPath);
+
+        Console.WriteLine("\n[示例 7 完成]\n");
+        await Task.CompletedTask;
+    }
+}

+ 82 - 0
Samples/Apq.Cfg.Samples/Demos/DynamicReloadDemo.cs

@@ -0,0 +1,82 @@
+using Apq.Cfg.Changes;
+using Microsoft.Extensions.Primitives;
+
+namespace Apq.Cfg.Samples.Demos;
+
+/// <summary>
+/// 示例 6: 动态配置重载
+/// </summary>
+public static class DynamicReloadDemo
+{
+    public static async Task RunAsync(string baseDir)
+    {
+        Console.WriteLine("═══════════════════════════════════════════════════════════════");
+        Console.WriteLine("示例 6: 动态配置重载");
+        Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
+
+        var configPath = Path.Combine(baseDir, "reload-demo.json");
+        File.WriteAllText(configPath, """
+        {
+            "App": {
+                "RefreshInterval": "30"
+            }
+        }
+        """);
+
+        // 启用 reloadOnChange
+        var cfg = new CfgBuilder()
+            .AddJson(configPath, level: 0, writeable: true, isPrimaryWriter: true, reloadOnChange: true)
+            .Build();
+
+        Console.WriteLine("6.1 配置动态重载选项:");
+        var msConfig = cfg.ToMicrosoftConfiguration(new DynamicReloadOptions
+        {
+            DebounceMs = 100,                    // 防抖时间
+            EnableDynamicReload = true,          // 启用动态重载
+            Strategy = ReloadStrategy.Eager,     // 立即重载
+            RollbackOnError = true,              // 错误时回滚
+            HistorySize = 5                      // 保留 5 条历史
+        });
+        Console.WriteLine("    已配置: DebounceMs=100, Strategy=Eager, HistorySize=5");
+
+        // 使用 IChangeToken 监听变更
+        Console.WriteLine("\n6.2 使用 IChangeToken 监听变更:");
+        var changeCount = 0;
+        ChangeToken.OnChange(
+            () => msConfig.GetReloadToken(),
+            () =>
+            {
+                changeCount++;
+                Console.WriteLine($"    [IChangeToken] 配置已更新 (第 {changeCount} 次)");
+            });
+        Console.WriteLine("    已注册 IChangeToken 回调");
+
+        // 使用 Rx 订阅配置变更
+        Console.WriteLine("\n6.3 使用 Rx 订阅配置变更:");
+        using var subscription = cfg.ConfigChanges.Subscribe(e =>
+        {
+            Console.WriteLine($"    [Rx] 批次 {e.BatchId} - {e.Changes.Count} 个变更:");
+            foreach (var (key, change) in e.Changes)
+            {
+                Console.WriteLine($"         [{change.Type}] {key}: {change.OldValue} -> {change.NewValue}");
+            }
+        });
+        Console.WriteLine("    已订阅 ConfigChanges");
+
+        // 模拟配置变更
+        Console.WriteLine("\n6.4 模拟配置变更:");
+        Console.WriteLine("    修改 App:RefreshInterval 为 60...");
+        cfg.Set("App:RefreshInterval", "60");
+        await cfg.SaveAsync();
+
+        // 等待变更通知
+        await Task.Delay(200);
+
+        Console.WriteLine($"\n    当前值: App:RefreshInterval = {cfg.Get("App:RefreshInterval")}");
+
+        cfg.Dispose();
+        File.Delete(configPath);
+
+        Console.WriteLine("\n[示例 6 完成]\n");
+    }
+}

+ 71 - 0
Samples/Apq.Cfg.Samples/Demos/EncodingMappingDemo.cs

@@ -0,0 +1,71 @@
+using System.Text;
+
+namespace Apq.Cfg.Samples.Demos;
+
+/// <summary>
+/// 示例 8: 编码映射配置
+/// </summary>
+public static class EncodingMappingDemo
+{
+    public static async Task RunAsync(string baseDir)
+    {
+        Console.WriteLine("═══════════════════════════════════════════════════════════════");
+        Console.WriteLine("示例 8: 编码映射配置");
+        Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
+
+        var configPath = Path.Combine(baseDir, "encoding-demo.json");
+        File.WriteAllText(configPath, """
+        {
+            "App": {
+                "Name": "编码测试应用",
+                "Description": "支持中文和特殊字符: äöü ñ 日本語"
+            }
+        }
+        """, Encoding.UTF8);
+
+        Console.WriteLine("8.1 编码检测置信度阈值:");
+        var cfg1 = new CfgBuilder()
+            .WithEncodingConfidenceThreshold(0.7f)
+            .AddJson(configPath, level: 0, writeable: false)
+            .Build();
+        Console.WriteLine($"    置信度阈值设置为 0.7");
+        Console.WriteLine($"    App:Name = {cfg1.Get("App:Name")}");
+        cfg1.Dispose();
+
+        Console.WriteLine("\n8.2 编码检测日志:");
+        var cfg2 = new CfgBuilder()
+            .WithEncodingDetectionLogging(result =>
+            {
+                Console.WriteLine($"    [编码检测] 文件: {Path.GetFileName(result.FilePath)}");
+                Console.WriteLine($"               编码: {result.Encoding.EncodingName}");
+                Console.WriteLine($"               置信度: {result.Confidence:P0}");
+                Console.WriteLine($"               方法: {result.Method}");
+            })
+            .AddJson(configPath, level: 0, writeable: false)
+            .Build();
+        cfg2.Dispose();
+
+        Console.WriteLine("\n8.3 编码映射规则:");
+        Console.WriteLine("    支持三种映射方式:");
+        Console.WriteLine("    - 完整路径: AddReadEncodingMapping(path, encoding)");
+        Console.WriteLine("    - 通配符:   AddReadEncodingMappingWildcard(\"*.json\", encoding)");
+        Console.WriteLine("    - 正则:     AddReadEncodingMappingRegex(@\"config.*\\.json$\", encoding)");
+
+        // 演示编码映射配置
+        var cfg3 = new CfgBuilder()
+            // 为特定文件指定编码
+            .AddReadEncodingMapping(configPath, Encoding.UTF8, priority: 100)
+            // 为所有 JSON 文件指定写入编码
+            .AddWriteEncodingMappingWildcard("*.json", new UTF8Encoding(false), priority: 50)
+            .AddJson(configPath, level: 0, writeable: false)
+            .Build();
+        Console.WriteLine("\n    已配置编码映射规则");
+        Console.WriteLine($"    App:Description = {cfg3.Get("App:Description")}");
+        cfg3.Dispose();
+
+        File.Delete(configPath);
+
+        Console.WriteLine("\n[示例 8 完成]\n");
+        await Task.CompletedTask;
+    }
+}

+ 220 - 0
Samples/Apq.Cfg.Samples/Demos/EtcdDemo.cs

@@ -0,0 +1,220 @@
+using Apq.Cfg;
+using Apq.Cfg.Etcd;
+
+namespace Apq.Cfg.Samples.Demos;
+
+/// <summary>
+/// 示例 12: Etcd 配置中心
+/// 演示如何使用 Etcd 作为配置源
+/// </summary>
+public static class EtcdDemo
+{
+    public static async Task RunAsync(string baseDir)
+    {
+        Console.WriteLine("═══════════════════════════════════════════════════════════════");
+        Console.WriteLine("示例 12: Etcd 配置中心");
+        Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
+
+        // 注意:此示例需要运行中的 Etcd 服务
+        // 可以使用 Docker 快速启动:docker run -d -p 2379:2379 -p 2380:2380 \
+        //   --name etcd quay.io/coreos/etcd:v3.5.0 \
+        //   /usr/local/bin/etcd --advertise-client-urls http://0.0.0.0:2379 \
+        //   --listen-client-urls http://0.0.0.0:2379
+        
+        Console.WriteLine("【Etcd 配置源说明】");
+        Console.WriteLine("Etcd 是一个分布式键值存储系统,常用于服务发现和配置管理。");
+        Console.WriteLine("Apq.Cfg.Etcd 支持从 Etcd v3 API 读取配置。\n");
+
+        // 示例 1: 基本配置
+        Console.WriteLine("--- 示例 12.1: 基本配置 ---");
+        ShowBasicConfiguration();
+
+        // 示例 2: 集群配置
+        Console.WriteLine("\n--- 示例 12.2: 集群配置 ---");
+        ShowClusterConfiguration();
+
+        // 示例 3: 认证配置
+        Console.WriteLine("\n--- 示例 12.3: 认证配置 ---");
+        ShowAuthConfiguration();
+
+        // 示例 4: TLS/mTLS 配置
+        Console.WriteLine("\n--- 示例 12.4: TLS/mTLS 配置 ---");
+        ShowTlsConfiguration();
+
+        // 示例 5: 监听配置变更
+        Console.WriteLine("\n--- 示例 12.5: 监听配置变更 ---");
+        ShowWatchConfiguration();
+
+        // 示例 6: 实际连接测试
+        Console.WriteLine("\n--- 示例 12.6: 连接测试 ---");
+        await TestConnectionAsync();
+
+        Console.WriteLine("\n示例 12 完成\n");
+    }
+
+    private static void ShowBasicConfiguration()
+    {
+        Console.WriteLine("基本配置代码示例:");
+        Console.WriteLine(@"
+// 使用 Action 配置
+var cfg = new CfgBuilder()
+    .AddEtcd(options =>
+    {
+        options.Endpoints = new[] { ""localhost:2379"" };  // Etcd 端点
+        options.KeyPrefix = ""/myapp/config/"";            // 键前缀
+    }, level: 0)
+    .Build();
+
+// 或使用简化方法(单端点)
+var cfg2 = new CfgBuilder()
+    .AddEtcd(""localhost:2379"", keyPrefix: ""/myapp/config/"")
+    .Build();
+
+// 读取配置
+var host = cfg.Get(""Database:Host"");
+");
+    }
+
+    private static void ShowClusterConfiguration()
+    {
+        Console.WriteLine("集群配置(多端点):");
+        Console.WriteLine(@"
+// Etcd 集群通常有多个节点,配置多个端点可提高可用性
+var cfg = new CfgBuilder()
+    .AddEtcd(options =>
+    {
+        options.Endpoints = new[]
+        {
+            ""etcd1.example.com:2379"",
+            ""etcd2.example.com:2379"",
+            ""etcd3.example.com:2379""
+        };
+        options.KeyPrefix = ""/myapp/config/"";
+        options.ConnectTimeout = TimeSpan.FromSeconds(10);
+        options.ReconnectInterval = TimeSpan.FromSeconds(5);
+    }, level: 0)
+    .Build();
+
+// 或使用简化方法(多端点)
+var cfg2 = new CfgBuilder()
+    .AddEtcd(
+        new[] { ""etcd1:2379"", ""etcd2:2379"", ""etcd3:2379"" },
+        keyPrefix: ""/myapp/config/"")
+    .Build();
+");
+    }
+
+    private static void ShowAuthConfiguration()
+    {
+        Console.WriteLine("用户名密码认证:");
+        Console.WriteLine(@"
+var cfg = new CfgBuilder()
+    .AddEtcd(options =>
+    {
+        options.Endpoints = new[] { ""localhost:2379"" };
+        options.KeyPrefix = ""/myapp/config/"";
+        options.Username = ""root"";           // 用户名
+        options.Password = ""your-password"";  // 密码
+    }, level: 0)
+    .Build();
+");
+    }
+
+    private static void ShowTlsConfiguration()
+    {
+        Console.WriteLine("TLS/mTLS 安全连接:");
+        Console.WriteLine(@"
+// TLS 连接(仅验证服务器证书)
+var cfg1 = new CfgBuilder()
+    .AddEtcd(options =>
+    {
+        options.Endpoints = new[] { ""etcd.example.com:2379"" };
+        options.KeyPrefix = ""/myapp/config/"";
+        options.CaCertPath = ""/path/to/ca.crt"";  // CA 证书
+    }, level: 0)
+    .Build();
+
+// mTLS 连接(双向认证)
+var cfg2 = new CfgBuilder()
+    .AddEtcd(options =>
+    {
+        options.Endpoints = new[] { ""etcd.example.com:2379"" };
+        options.KeyPrefix = ""/myapp/config/"";
+        options.CaCertPath = ""/path/to/ca.crt"";          // CA 证书
+        options.ClientCertPath = ""/path/to/client.crt"";  // 客户端证书
+        options.ClientKeyPath = ""/path/to/client.key"";   // 客户端私钥
+    }, level: 0)
+    .Build();
+");
+    }
+
+    private static void ShowWatchConfiguration()
+    {
+        Console.WriteLine("监听配置变更:");
+        Console.WriteLine(@"
+var cfg = new CfgBuilder()
+    .AddEtcd(options =>
+    {
+        options.Endpoints = new[] { ""localhost:2379"" };
+        options.KeyPrefix = ""/myapp/config/"";
+        options.EnableHotReload = true;  // 启用热重载(默认 true)
+    }, level: 0)
+    .Build();
+
+// 订阅配置变更(使用 Etcd Watch API)
+cfg.ConfigChanges.Subscribe(change =>
+{
+    Console.WriteLine($""配置变更: {change.Key}"");
+    Console.WriteLine($""  旧值: {change.OldValue}"");
+    Console.WriteLine($""  新值: {change.NewValue}"");
+    Console.WriteLine($""  类型: {change.ChangeType}"");
+});
+
+// 不同数据格式
+var cfgJson = new CfgBuilder()
+    .AddEtcd(options =>
+    {
+        options.Endpoints = new[] { ""localhost:2379"" };
+        options.KeyPrefix = ""/myapp/"";
+        options.DataFormat = EtcdDataFormat.Json;  // JSON 格式
+        options.SingleKey = ""config"";            // 读取 /myapp/config
+    }, level: 0)
+    .Build();
+");
+    }
+
+    private static async Task TestConnectionAsync()
+    {
+        Console.WriteLine("尝试连接本地 Etcd...");
+        
+        try
+        {
+            var cfg = new CfgBuilder()
+                .AddEtcd(options =>
+                {
+                    options.Endpoints = new[] { "localhost:2379" };
+                    options.KeyPrefix = "/apq-cfg-demo/";
+                    options.ConnectTimeout = TimeSpan.FromSeconds(3);
+                }, level: 0)
+                .Build();
+
+            // 尝试读取配置
+            var testValue = cfg.Get("test");
+            Console.WriteLine($"✓ 连接成功!test 键的值: {testValue ?? "(空)"}");
+            
+            // 显示所有键
+            var keys = cfg.GetChildKeys();
+            Console.WriteLine($"  配置键数量: {keys.Count()}");
+        }
+        catch (Exception ex)
+        {
+            Console.WriteLine($"✗ 连接失败: {ex.Message}");
+            Console.WriteLine("  提示: 请确保 Etcd 服务正在运行");
+            Console.WriteLine("  快速启动: docker run -d -p 2379:2379 quay.io/coreos/etcd:v3.5.0 \\");
+            Console.WriteLine("    /usr/local/bin/etcd --advertise-client-urls http://0.0.0.0:2379 \\");
+            Console.WriteLine("    --listen-client-urls http://0.0.0.0:2379");
+        }
+        
+        await Task.CompletedTask;
+    }
+}

+ 118 - 0
Samples/Apq.Cfg.Samples/Demos/MultiFormatDemo.cs

@@ -0,0 +1,118 @@
+using Apq.Cfg.Ini;
+using Apq.Cfg.Xml;
+using Apq.Cfg.Yaml;
+using Apq.Cfg.Toml;
+
+namespace Apq.Cfg.Samples.Demos;
+
+/// <summary>
+/// 示例 2: 多格式支持 - INI、XML、YAML、TOML
+/// </summary>
+public static class MultiFormatDemo
+{
+    public static async Task RunAsync(string baseDir)
+    {
+        Console.WriteLine("═══════════════════════════════════════════════════════════════");
+        Console.WriteLine("示例 2: 多格式支持 - INI、XML、YAML、TOML");
+        Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
+
+        // INI 格式
+        var iniPath = Path.Combine(baseDir, "config.ini");
+        File.WriteAllText(iniPath, """
+        [App]
+        Name=IniApp
+        Version=2.0.0
+
+        [Database]
+        Host=ini-server
+        Port=5432
+        """);
+
+        // XML 格式
+        var xmlPath = Path.Combine(baseDir, "config.xml");
+        File.WriteAllText(xmlPath, """
+        <?xml version="1.0" encoding="utf-8"?>
+        <configuration>
+            <App>
+                <Name>XmlApp</Name>
+                <Version>3.0.0</Version>
+            </App>
+            <Database>
+                <Host>xml-server</Host>
+                <Port>1433</Port>
+            </Database>
+        </configuration>
+        """);
+
+        // YAML 格式
+        var yamlPath = Path.Combine(baseDir, "config.yaml");
+        File.WriteAllText(yamlPath, """
+        App:
+          Name: YamlApp
+          Version: 4.0.0
+        Database:
+          Host: yaml-server
+          Port: 27017
+        """);
+
+        // TOML 格式
+        var tomlPath = Path.Combine(baseDir, "config.toml");
+        File.WriteAllText(tomlPath, """
+        [App]
+        Name = "TomlApp"
+        Version = "5.0.0"
+
+        [Database]
+        Host = "toml-server"
+        Port = 6379
+        """);
+
+        // 分别测试各格式
+        Console.WriteLine("2.1 INI 格式:");
+        using (var iniCfg = new CfgBuilder().AddIni(iniPath, level: 0, writeable: true).Build())
+        {
+            Console.WriteLine($"    App:Name = {iniCfg.Get("App:Name")}");
+            Console.WriteLine($"    Database:Port = {iniCfg.Get("Database:Port")}");
+        }
+
+        Console.WriteLine("\n2.2 XML 格式:");
+        using (var xmlCfg = new CfgBuilder().AddXml(xmlPath, level: 0, writeable: true).Build())
+        {
+            Console.WriteLine($"    App:Name = {xmlCfg.Get("App:Name")}");
+            Console.WriteLine($"    Database:Port = {xmlCfg.Get("Database:Port")}");
+        }
+
+        Console.WriteLine("\n2.3 YAML 格式:");
+        using (var yamlCfg = new CfgBuilder().AddYaml(yamlPath, level: 0, writeable: true).Build())
+        {
+            Console.WriteLine($"    App:Name = {yamlCfg.Get("App:Name")}");
+            Console.WriteLine($"    Database:Port = {yamlCfg.Get("Database:Port")}");
+        }
+
+        Console.WriteLine("\n2.4 TOML 格式:");
+        using (var tomlCfg = new CfgBuilder().AddToml(tomlPath, level: 0, writeable: true).Build())
+        {
+            Console.WriteLine($"    App:Name = {tomlCfg.Get("App:Name")}");
+            Console.WriteLine($"    Database:Port = {tomlCfg.Get("Database:Port")}");
+        }
+
+        // 混合多种格式
+        Console.WriteLine("\n2.5 混合多种格式(层级覆盖):");
+        using var mixedCfg = new CfgBuilder()
+            .AddIni(iniPath, level: 0, writeable: false)
+            .AddYaml(yamlPath, level: 1, writeable: false)
+            .AddToml(tomlPath, level: 2, writeable: true, isPrimaryWriter: true)
+            .Build();
+
+        Console.WriteLine($"    App:Name = {mixedCfg.Get("App:Name")} (来自 TOML,最高优先级)");
+        Console.WriteLine($"    App:Version = {mixedCfg.Get("App:Version")} (来自 TOML)");
+
+        File.Delete(iniPath);
+        File.Delete(xmlPath);
+        File.Delete(yamlPath);
+        File.Delete(tomlPath);
+
+        Console.WriteLine("\n[示例 2 完成]\n");
+        await Task.CompletedTask;
+    }
+}

+ 247 - 0
Samples/Apq.Cfg.Samples/Demos/NacosDemo.cs

@@ -0,0 +1,247 @@
+using Apq.Cfg;
+using Apq.Cfg.Nacos;
+
+namespace Apq.Cfg.Samples.Demos;
+
+/// <summary>
+/// 示例 13: Nacos 配置中心
+/// 演示如何使用 Nacos 作为配置源
+/// </summary>
+public static class NacosDemo
+{
+    public static async Task RunAsync(string baseDir)
+    {
+        Console.WriteLine("═══════════════════════════════════════════════════════════════");
+        Console.WriteLine("示例 13: Nacos 配置中心");
+        Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
+
+        // 注意:此示例需要运行中的 Nacos 服务
+        // 可以使用 Docker 快速启动:
+        // docker run -d -p 8848:8848 -e MODE=standalone nacos/nacos-server:latest
+        
+        Console.WriteLine("【Nacos 配置源说明】");
+        Console.WriteLine("Nacos 是阿里巴巴开源的服务发现和配置管理平台。");
+        Console.WriteLine("Apq.Cfg.Nacos 支持从 Nacos 配置中心读取配置。\n");
+
+        // 示例 1: 基本配置
+        Console.WriteLine("--- 示例 13.1: 基本配置 ---");
+        ShowBasicConfiguration();
+
+        // 示例 2: 命名空间和分组
+        Console.WriteLine("\n--- 示例 13.2: 命名空间和分组 ---");
+        ShowNamespaceConfiguration();
+
+        // 示例 3: 认证配置
+        Console.WriteLine("\n--- 示例 13.3: 认证配置 ---");
+        ShowAuthConfiguration();
+
+        // 示例 4: 阿里云 MSE 配置
+        Console.WriteLine("\n--- 示例 13.4: 阿里云 MSE 配置 ---");
+        ShowAliyunMseConfiguration();
+
+        // 示例 5: 多配置源
+        Console.WriteLine("\n--- 示例 13.5: 多配置源 ---");
+        ShowMultipleDataIdConfiguration();
+
+        // 示例 6: 不同数据格式
+        Console.WriteLine("\n--- 示例 13.6: 不同数据格式 ---");
+        ShowDataFormatConfiguration();
+
+        // 示例 7: 实际连接测试
+        Console.WriteLine("\n--- 示例 13.7: 连接测试 ---");
+        await TestConnectionAsync();
+
+        Console.WriteLine("\n示例 13 完成\n");
+    }
+
+    private static void ShowBasicConfiguration()
+    {
+        Console.WriteLine("基本配置代码示例:");
+        Console.WriteLine(@"
+// 使用 Action 配置
+var cfg = new CfgBuilder()
+    .AddNacos(options =>
+    {
+        options.ServerAddresses = ""localhost:8848"";  // Nacos 服务地址
+        options.DataId = ""myapp-config"";             // 配置 DataId
+        options.Group = ""DEFAULT_GROUP"";             // 配置分组
+    }, level: 0)
+    .Build();
+
+// 或使用简化方法
+var cfg2 = new CfgBuilder()
+    .AddNacos(""localhost:8848"", dataId: ""myapp-config"")
+    .Build();
+
+// 读取配置
+var host = cfg.Get(""Database:Host"");
+");
+    }
+
+    private static void ShowNamespaceConfiguration()
+    {
+        Console.WriteLine("命名空间和分组配置:");
+        Console.WriteLine(@"
+// Nacos 支持命名空间隔离不同环境的配置
+var cfg = new CfgBuilder()
+    .AddNacos(options =>
+    {
+        options.ServerAddresses = ""localhost:8848"";
+        options.Namespace = ""dev"";           // 命名空间 ID(开发环境)
+        options.DataId = ""myapp-config"";
+        options.Group = ""MYAPP_GROUP"";       // 自定义分组
+    }, level: 0)
+    .Build();
+
+// 生产环境配置
+var cfgProd = new CfgBuilder()
+    .AddNacos(options =>
+    {
+        options.ServerAddresses = ""nacos.prod.example.com:8848"";
+        options.Namespace = ""prod"";          // 生产命名空间
+        options.DataId = ""myapp-config"";
+        options.Group = ""MYAPP_GROUP"";
+    }, level: 0)
+    .Build();
+");
+    }
+
+    private static void ShowAuthConfiguration()
+    {
+        Console.WriteLine("用户名密码认证:");
+        Console.WriteLine(@"
+var cfg = new CfgBuilder()
+    .AddNacos(options =>
+    {
+        options.ServerAddresses = ""localhost:8848"";
+        options.DataId = ""myapp-config"";
+        options.Group = ""DEFAULT_GROUP"";
+        options.Username = ""nacos"";          // 用户名
+        options.Password = ""nacos"";          // 密码
+        options.ConnectTimeoutMs = 10000;      // 连接超时(毫秒)
+    }, level: 0)
+    .Build();
+");
+    }
+
+    private static void ShowAliyunMseConfiguration()
+    {
+        Console.WriteLine("阿里云 MSE(微服务引擎)配置:");
+        Console.WriteLine(@"
+// 使用阿里云 MSE 托管的 Nacos
+var cfg = new CfgBuilder()
+    .AddNacos(options =>
+    {
+        options.ServerAddresses = ""mse-xxx.nacos.mse.aliyuncs.com:8848"";
+        options.Namespace = ""your-namespace-id"";
+        options.DataId = ""myapp-config"";
+        options.Group = ""DEFAULT_GROUP"";
+        options.AccessKey = ""your-access-key"";   // 阿里云 AccessKey
+        options.SecretKey = ""your-secret-key"";   // 阿里云 SecretKey
+    }, level: 0)
+    .Build();
+");
+    }
+
+    private static void ShowMultipleDataIdConfiguration()
+    {
+        Console.WriteLine("多配置源(多 DataId):");
+        Console.WriteLine(@"
+// 可以加载多个配置,实现配置的层级覆盖
+var cfg = new CfgBuilder()
+    // 公共配置(最低优先级)
+    .AddNacos(options =>
+    {
+        options.ServerAddresses = ""localhost:8848"";
+        options.DataId = ""common-config"";
+        options.Group = ""DEFAULT_GROUP"";
+    }, level: 0)
+    // 应用配置(中等优先级)
+    .AddNacos(options =>
+    {
+        options.ServerAddresses = ""localhost:8848"";
+        options.DataId = ""myapp-config"";
+        options.Group = ""DEFAULT_GROUP"";
+    }, level: 1)
+    // 环境特定配置(最高优先级)
+    .AddNacos(options =>
+    {
+        options.ServerAddresses = ""localhost:8848"";
+        options.DataId = ""myapp-config-dev"";
+        options.Group = ""DEFAULT_GROUP"";
+    }, level: 2)
+    .Build();
+");
+    }
+
+    private static void ShowDataFormatConfiguration()
+    {
+        Console.WriteLine("不同数据格式配置:");
+        Console.WriteLine(@"
+// 1. JSON 格式(默认)
+var cfgJson = new CfgBuilder()
+    .AddNacos(options =>
+    {
+        options.ServerAddresses = ""localhost:8848"";
+        options.DataId = ""myapp-config.json"";
+        options.DataFormat = NacosDataFormat.Json;
+    }, level: 0)
+    .Build();
+
+// 2. YAML 格式
+var cfgYaml = new CfgBuilder()
+    .AddNacos(options =>
+    {
+        options.ServerAddresses = ""localhost:8848"";
+        options.DataId = ""myapp-config.yaml"";
+        options.DataFormat = NacosDataFormat.Yaml;
+    }, level: 0)
+    .Build();
+
+// 3. Properties 格式(key=value)
+var cfgProps = new CfgBuilder()
+    .AddNacos(options =>
+    {
+        options.ServerAddresses = ""localhost:8848"";
+        options.DataId = ""myapp-config.properties"";
+        options.DataFormat = NacosDataFormat.Properties;
+    }, level: 0)
+    .Build();
+");
+    }
+
+    private static async Task TestConnectionAsync()
+    {
+        Console.WriteLine("尝试连接本地 Nacos...");
+        
+        try
+        {
+            var cfg = new CfgBuilder()
+                .AddNacos(options =>
+                {
+                    options.ServerAddresses = "localhost:8848";
+                    options.DataId = "apq-cfg-demo";
+                    options.Group = "DEFAULT_GROUP";
+                    options.ConnectTimeoutMs = 3000;
+                }, level: 0)
+                .Build();
+
+            // 尝试读取配置
+            var testValue = cfg.Get("test");
+            Console.WriteLine($"✓ 连接成功!test 键的值: {testValue ?? "(空)"}");
+            
+            // 显示所有键
+            var keys = cfg.GetChildKeys();
+            Console.WriteLine($"  配置键数量: {keys.Count()}");
+        }
+        catch (Exception ex)
+        {
+            Console.WriteLine($"✗ 连接失败: {ex.Message}");
+            Console.WriteLine("  提示: 请确保 Nacos 服务正在运行");
+            Console.WriteLine("  快速启动: docker run -d -p 8848:8848 -e MODE=standalone nacos/nacos-server:latest");
+            Console.WriteLine("  控制台: http://localhost:8848/nacos (用户名/密码: nacos/nacos)");
+        }
+        
+        await Task.CompletedTask;
+    }
+}

+ 74 - 0
Samples/Apq.Cfg.Samples/Demos/RedisDemo.cs

@@ -0,0 +1,74 @@
+using Apq.Cfg.Redis;
+
+namespace Apq.Cfg.Samples.Demos;
+
+/// <summary>
+/// 示例 9: Redis 配置源
+/// 注意:需要运行 Redis 服务才能执行此示例
+/// </summary>
+public static class RedisDemo
+{
+    public static async Task RunAsync(string baseDir)
+    {
+        Console.WriteLine("═══════════════════════════════════════════════════════════════");
+        Console.WriteLine("示例 9: Redis 配置源");
+        Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
+
+        Console.WriteLine("注意:此示例需要运行 Redis 服务 (localhost:6379)\n");
+
+        try
+        {
+            // 构建 Redis 配置源
+            Console.WriteLine("9.1 连接 Redis 配置源:");
+            var cfg = new CfgBuilder()
+                .AddRedis(options =>
+                {
+                    options.ConnectionString = "localhost:6379";
+                    options.KeyPrefix = "apq:samples:";
+                    options.Database = 0;
+                    options.ConnectTimeoutMs = 3000;
+                }, level: 0, isPrimaryWriter: true)
+                .Build();
+
+            Console.WriteLine("    已连接到 Redis");
+
+            // 写入配置
+            Console.WriteLine("\n9.2 写入配置到 Redis:");
+            cfg.Set("App:Name", "RedisApp");
+            cfg.Set("App:Version", "1.0.0");
+            cfg.Set("Database:Host", "db.example.com");
+            cfg.Set("Database:Port", "5432");
+            await cfg.SaveAsync();
+            Console.WriteLine("    已写入 4 个配置项");
+
+            // 读取配置
+            Console.WriteLine("\n9.3 从 Redis 读取配置:");
+            Console.WriteLine($"    App:Name = {cfg.Get("App:Name")}");
+            Console.WriteLine($"    App:Version = {cfg.Get("App:Version")}");
+            Console.WriteLine($"    Database:Host = {cfg.Get("Database:Host")}");
+            Console.WriteLine($"    Database:Port = {cfg.Get<int>("Database:Port")}");
+
+            // 检查配置是否存在
+            Console.WriteLine("\n9.4 检查配置是否存在:");
+            Console.WriteLine($"    Exists(App:Name) = {cfg.Exists("App:Name")}");
+            Console.WriteLine($"    Exists(NotExist) = {cfg.Exists("NotExist")}");
+
+            // 删除配置
+            Console.WriteLine("\n9.5 删除配置:");
+            cfg.Remove("App:Name");
+            cfg.Remove("App:Version");
+            cfg.Remove("Database:Host");
+            cfg.Remove("Database:Port");
+            await cfg.SaveAsync();
+            Console.WriteLine("    已清理测试配置");
+
+            cfg.Dispose();
+            Console.WriteLine("\n[示例 9 完成]\n");
+        }
+        catch (Exception ex)
+        {
+            Console.WriteLine($"    [跳过] Redis 服务不可用: {ex.Message}");
+            Console.WriteLine("\n[示例 9 跳过]\n");
+        }
+    }
+}

+ 358 - 0
Samples/Apq.Cfg.Samples/Demos/SourceGeneratorDemo.cs

@@ -0,0 +1,358 @@
+using Apq.Cfg;
+
+namespace Apq.Cfg.Samples.Demos;
+
+/// <summary>
+/// 示例 17: 源生成器(零反射绑定)
+/// 演示如何使用 Apq.Cfg.SourceGenerator 实现零反射配置绑定
+/// </summary>
+public static class SourceGeneratorDemo
+{
+    public static async Task RunAsync(string baseDir)
+    {
+        Console.WriteLine("═══════════════════════════════════════════════════════════════");
+        Console.WriteLine("示例 17: 源生成器(零反射绑定)");
+        Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
+
+        Console.WriteLine("【源生成器说明】");
+        Console.WriteLine("Apq.Cfg.SourceGenerator 使用 Roslyn 源生成器在编译时生成配置绑定代码。");
+        Console.WriteLine("优势:零反射、Native AOT 兼容、编译时类型检查。\n");
+
+        // 示例 1: 基本用法
+        Console.WriteLine("--- 示例 17.1: 基本用法 ---");
+        ShowBasicUsage();
+
+        // 示例 2: 定义配置类
+        Console.WriteLine("\n--- 示例 17.2: 定义配置类 ---");
+        ShowConfigClassDefinition();
+
+        // 示例 3: 使用生成的绑定方法
+        Console.WriteLine("\n--- 示例 17.3: 使用生成的绑定方法 ---");
+        ShowBindingMethods();
+
+        // 示例 4: 支持的类型
+        Console.WriteLine("\n--- 示例 17.4: 支持的类型 ---");
+        ShowSupportedTypes();
+
+        // 示例 5: 嵌套配置
+        Console.WriteLine("\n--- 示例 17.5: 嵌套配置 ---");
+        ShowNestedConfiguration();
+
+        // 示例 6: 集合类型
+        Console.WriteLine("\n--- 示例 17.6: 集合类型 ---");
+        ShowCollectionTypes();
+
+        // 示例 7: 查看生成的代码
+        Console.WriteLine("\n--- 示例 17.7: 查看生成的代码 ---");
+        ShowGeneratedCode();
+
+        // 示例 8: 实际演示
+        Console.WriteLine("\n--- 示例 17.8: 实际演示 ---");
+        await DemoActualUsageAsync(baseDir);
+
+        Console.WriteLine("\n示例 17 完成\n");
+    }
+
+    private static void ShowBasicUsage()
+    {
+        Console.WriteLine("基本用法:");
+        Console.WriteLine(@"
+// 1. 安装 NuGet 包
+// dotnet add package Apq.Cfg.SourceGenerator
+
+// 2. 定义配置类(必须是 partial 类)
+[CfgSection(""AppSettings"")]
+public partial class AppConfig
+{
+    public string? Name { get; set; }
+    public int Port { get; set; }
+}
+
+// 3. 使用生成的绑定方法
+var cfg = new CfgBuilder()
+    .AddJson(""config.json"")
+    .Build();
+
+var appConfig = AppConfig.BindFrom(cfg.GetSection(""AppSettings""));
+Console.WriteLine($""Name: {appConfig.Name}, Port: {appConfig.Port}"");
+");
+    }
+
+    private static void ShowConfigClassDefinition()
+    {
+        Console.WriteLine("配置类定义规则:");
+        Console.WriteLine(@"
+// 1. 使用 [CfgSection] 特性标记
+// 2. 类必须是 partial 的
+// 3. 属性必须有 public getter 和 setter
+
+using Apq.Cfg;
+
+// 指定配置节路径
+[CfgSection(""Database"")]
+public partial class DatabaseConfig
+{
+    public string? Host { get; set; }
+    public int Port { get; set; } = 5432;  // 支持默认值
+    public string? Name { get; set; }
+}
+
+// 不指定路径时,使用类名(去掉 Config/Settings 后缀)
+[CfgSection]
+public partial class LoggingConfig
+{
+    public string? Level { get; set; }
+    public bool EnableConsole { get; set; }
+}
+
+// 禁用扩展方法生成
+[CfgSection(""Cache"", GenerateExtension = false)]
+public partial class CacheConfig
+{
+    public string? Provider { get; set; }
+    public int ExpirationMinutes { get; set; }
+}
+");
+    }
+
+    private static void ShowBindingMethods()
+    {
+        Console.WriteLine("生成的绑定方法:");
+        Console.WriteLine(@"
+// 源生成器会为每个配置类生成以下方法:
+
+// 1. BindFrom - 从配置节创建新实例
+var config = DatabaseConfig.BindFrom(cfgRoot.GetSection(""Database""));
+
+// 2. BindTo - 绑定到已有实例
+var existingConfig = new DatabaseConfig();
+DatabaseConfig.BindTo(cfgRoot.GetSection(""Database""), existingConfig);
+
+// 3. 扩展方法(如果指定了 SectionPath)
+var config2 = cfgRoot.GetDatabaseConfig();  // 自动生成的扩展方法
+");
+    }
+
+    private static void ShowSupportedTypes()
+    {
+        Console.WriteLine("支持的类型:");
+        Console.WriteLine(@"
+[CfgSection(""TypeDemo"")]
+public partial class TypeDemoConfig
+{
+    // 字符串
+    public string? StringValue { get; set; }
+
+    // 数值类型
+    public int IntValue { get; set; }
+    public long LongValue { get; set; }
+    public double DoubleValue { get; set; }
+    public decimal DecimalValue { get; set; }
+
+    // 布尔
+    public bool BoolValue { get; set; }
+
+    // 日期时间
+    public DateTime DateTimeValue { get; set; }
+    public DateTimeOffset DateTimeOffsetValue { get; set; }
+    public TimeSpan TimeSpanValue { get; set; }
+    public DateOnly DateOnlyValue { get; set; }  // .NET 6+
+    public TimeOnly TimeOnlyValue { get; set; }  // .NET 6+
+
+    // 其他
+    public Guid GuidValue { get; set; }
+    public Uri? UriValue { get; set; }
+
+    // 枚举
+    public LogLevel LogLevel { get; set; }
+
+    // 可空类型
+    public int? NullableInt { get; set; }
+    public DateTime? NullableDateTime { get; set; }
+}
+
+public enum LogLevel { Debug, Info, Warning, Error }
+");
+    }
+
+    private static void ShowNestedConfiguration()
+    {
+        Console.WriteLine("嵌套配置:");
+        Console.WriteLine(@"
+// 嵌套的配置类也需要标记 [CfgSection]
+[CfgSection(""App"")]
+public partial class AppConfig
+{
+    public string? Name { get; set; }
+    public DatabaseConfig? Database { get; set; }  // 嵌套对象
+    public LoggingConfig? Logging { get; set; }
+}
+
+[CfgSection]
+public partial class DatabaseConfig
+{
+    public string? ConnectionString { get; set; }
+    public int Timeout { get; set; } = 30;
+}
+
+[CfgSection]
+public partial class LoggingConfig
+{
+    public string? Level { get; set; }
+    public bool EnableConsole { get; set; }
+}
+
+// 对应的 JSON 配置:
+// {
+//   ""App"": {
+//     ""Name"": ""MyApp"",
+//     ""Database"": {
+//       ""ConnectionString"": ""Server=localhost;..."",
+//       ""Timeout"": 60
+//     },
+//     ""Logging"": {
+//       ""Level"": ""Info"",
+//       ""EnableConsole"": true
+//     }
+//   }
+// }
+");
+    }
+
+    private static void ShowCollectionTypes()
+    {
+        Console.WriteLine("集合类型:");
+        Console.WriteLine(@"
+[CfgSection(""Collections"")]
+public partial class CollectionsConfig
+{
+    // 数组
+    public string[]? Tags { get; set; }
+    public int[]? Ports { get; set; }
+
+    // List
+    public List<string>? Hosts { get; set; }
+
+    // HashSet
+    public HashSet<string>? AllowedOrigins { get; set; }
+
+    // Dictionary
+    public Dictionary<string, string>? Headers { get; set; }
+    public Dictionary<string, int>? Limits { get; set; }
+}
+
+// 对应的 JSON 配置:
+// {
+//   ""Collections"": {
+//     ""Tags"": [""web"", ""api"", ""v2""],
+//     ""Ports"": [80, 443, 8080],
+//     ""Hosts"": [""host1.com"", ""host2.com""],
+//     ""AllowedOrigins"": [""https://example.com""],
+//     ""Headers"": {
+//       ""X-Api-Key"": ""secret"",
+//       ""X-Version"": ""1.0""
+//     },
+//     ""Limits"": {
+//       ""MaxConnections"": 100,
+//       ""MaxRequests"": 1000
+//     }
+//   }
+// }
+");
+    }
+
+    private static void ShowGeneratedCode()
+    {
+        Console.WriteLine("查看生成的代码:");
+        Console.WriteLine(@"
+// 在项目文件中添加以下配置可以保留生成的源代码:
+<PropertyGroup>
+  <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
+  <CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GeneratedFiles</CompilerGeneratedFilesOutputPath>
+</PropertyGroup>
+
+// 生成的文件将位于 obj/GeneratedFiles/ 目录下
+
+// 生成的代码示例:
+partial class DatabaseConfig
+{
+    public static DatabaseConfig BindFrom(ICfgSection section)
+    {
+        if (section == null) throw new ArgumentNullException(nameof(section));
+        var result = new DatabaseConfig();
+        BindTo(section, result);
+        return result;
+    }
+
+    public static void BindTo(ICfgSection section, DatabaseConfig target)
+    {
+        if (section == null) throw new ArgumentNullException(nameof(section));
+        if (target == null) throw new ArgumentNullException(nameof(target));
+
+        // ConnectionString: string?
+        {
+            var __value = section.Get(""ConnectionString"");
+            if (__value != null)
+            {
+                target.ConnectionString = __value;
+            }
+        }
+
+        // Timeout: int
+        {
+            var __value = section.Get(""Timeout"");
+            if (__value != null)
+            {
+                var __converted = int.TryParse(__value, out var __intVal) ? __intVal : (int?)null;
+                if (__converted != null) target.Timeout = __converted.Value;
+            }
+        }
+    }
+}
+");
+    }
+
+    private static async Task DemoActualUsageAsync(string baseDir)
+    {
+        Console.WriteLine("实际演示(使用内存配置):");
+        
+        // 创建一个简单的配置
+        var cfg = new CfgBuilder()
+            .AddJson(Path.Combine(baseDir, "config.json"), level: 0, writeable: false, optional: true, reloadOnChange: false)
+            .Build();
+
+        // 由于源生成器需要在编译时生成代码,这里只能展示概念
+        Console.WriteLine(@"
+// 假设我们有以下配置类:
+// [CfgSection(""Database"")]
+// public partial class DatabaseConfig
+// {
+//     public string? Host { get; set; }
+//     public int Port { get; set; }
+//     public string? Name { get; set; }
+// }
+
+// 使用方式:
+// var dbConfig = DatabaseConfig.BindFrom(cfg.GetSection(""Database""));
+// Console.WriteLine($""Host: {dbConfig.Host}"");
+// Console.WriteLine($""Port: {dbConfig.Port}"");
+// Console.WriteLine($""Name: {dbConfig.Name}"");
+");
+
+        // 使用传统方式读取配置作为对比
+        var section = cfg.GetSection("Database");
+        Console.WriteLine("\n使用传统方式读取配置(对比):");
+        Console.WriteLine($"  Host: {section.Get("Host") ?? "(未配置)"}");
+        Console.WriteLine($"  Port: {section.Get("Port") ?? "(未配置)"}");
+        Console.WriteLine($"  Name: {section.Get("Name") ?? "(未配置)"}");
+
+        Console.WriteLine("\n源生成器的优势:");
+        Console.WriteLine("  ✓ 零反射 - 编译时生成绑定代码");
+        Console.WriteLine("  ✓ Native AOT 兼容 - 完全支持 AOT 发布");
+        Console.WriteLine("  ✓ 编译时类型检查 - 属性名错误会在编译时报错");
+        Console.WriteLine("  ✓ 更好的性能 - 无运行时反射开销");
+        Console.WriteLine("  ✓ IntelliSense 支持 - IDE 自动补全");
+
+        await Task.CompletedTask;
+    }
+}

+ 57 - 0
Samples/Apq.Cfg.Samples/Demos/TypeConversionDemo.cs

@@ -0,0 +1,57 @@
+using Apq.Cfg.Samples.Models;
+
+namespace Apq.Cfg.Samples.Demos;
+
+/// <summary>
+/// 示例 5: 类型转换
+/// </summary>
+public static class TypeConversionDemo
+{
+    public static async Task RunAsync(string baseDir)
+    {
+        Console.WriteLine("═══════════════════════════════════════════════════════════════");
+        Console.WriteLine("示例 5: 类型转换");
+        Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
+
+        var configPath = Path.Combine(baseDir, "types-demo.json");
+        File.WriteAllText(configPath, """
+        {
+            "Types": {
+                "IntValue": "42",
+                "LongValue": "9223372036854775807",
+                "DoubleValue": "3.14159",
+                "DecimalValue": "123.456",
+                "BoolTrue": "true",
+                "BoolFalse": "false",
+                "DateValue": "2024-12-25",
+                "GuidValue": "550e8400-e29b-41d4-a716-446655440000",
+                "EnumValue": "Warning"
+            }
+        }
+        """);
+
+        using var cfg = new CfgBuilder()
+            .AddJson(configPath, level: 0, writeable: false)
+            .Build();
+
+        Console.WriteLine("5.1 各种类型转换:");
+        Console.WriteLine($"    int: {cfg.Get<int>("Types:IntValue")}");
+        Console.WriteLine($"    long: {cfg.Get<long>("Types:LongValue")}");
+        Console.WriteLine($"    double: {cfg.Get<double>("Types:DoubleValue")}");
+        Console.WriteLine($"    decimal: {cfg.Get<decimal>("Types:DecimalValue")}");
+        Console.WriteLine($"    bool (true): {cfg.Get<bool>("Types:BoolTrue")}");
+        Console.WriteLine($"    bool (false): {cfg.Get<bool>("Types:BoolFalse")}");
+        Console.WriteLine($"    DateTime: {cfg.Get<DateTime>("Types:DateValue"):yyyy-MM-dd}");
+        Console.WriteLine($"    Guid: {cfg.Get<Guid>("Types:GuidValue")}");
+        Console.WriteLine($"    Enum: {cfg.Get<LogLevel>("Types:EnumValue")}");
+
+        Console.WriteLine("\n5.2 可空类型与默认值:");
+        Console.WriteLine($"    不存在的键 (int?): {cfg.Get<int?>("Types:NotExist") ?? -1}");
+        Console.WriteLine($"    不存在的键 (string): {cfg.Get("Types:NotExist") ?? "(null)"}");
+
+        File.Delete(configPath);
+
+        Console.WriteLine("\n[示例 5 完成]\n");
+        await Task.CompletedTask;
+    }
+}

+ 273 - 0
Samples/Apq.Cfg.Samples/Demos/VaultDemo.cs

@@ -0,0 +1,273 @@
+using Apq.Cfg;
+using Apq.Cfg.Vault;
+
+namespace Apq.Cfg.Samples.Demos;
+
+/// <summary>
+/// 示例 16: HashiCorp Vault 密钥管理
+/// 演示如何使用 Vault 作为配置源
+/// </summary>
+public static class VaultDemo
+{
+    public static async Task RunAsync(string baseDir)
+    {
+        Console.WriteLine("═══════════════════════════════════════════════════════════════");
+        Console.WriteLine("示例 16: HashiCorp Vault 密钥管理");
+        Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
+
+        // 注意:此示例需要运行中的 Vault 服务
+        // 可以使用 Docker 快速启动:
+        // docker run -d -p 8200:8200 -e VAULT_DEV_ROOT_TOKEN_ID=myroot vault
+        
+        Console.WriteLine("【Vault 配置源说明】");
+        Console.WriteLine("HashiCorp Vault 是一个密钥管理和数据保护工具。");
+        Console.WriteLine("Apq.Cfg.Vault 支持从 Vault KV 引擎读取配置和密钥。\n");
+
+        // 示例 1: Token 认证
+        Console.WriteLine("--- 示例 16.1: Token 认证 ---");
+        ShowTokenAuthConfiguration();
+
+        // 示例 2: KV V1 vs V2
+        Console.WriteLine("\n--- 示例 16.2: KV V1 vs V2 ---");
+        ShowKvVersionConfiguration();
+
+        // 示例 3: UserPass 认证
+        Console.WriteLine("\n--- 示例 16.3: UserPass 认证 ---");
+        ShowUserPassAuthConfiguration();
+
+        // 示例 4: AppRole 认证
+        Console.WriteLine("\n--- 示例 16.4: AppRole 认证 ---");
+        ShowAppRoleAuthConfiguration();
+
+        // 示例 5: 企业版命名空间
+        Console.WriteLine("\n--- 示例 16.5: 企业版命名空间 ---");
+        ShowNamespaceConfiguration();
+
+        // 示例 6: 热重载
+        Console.WriteLine("\n--- 示例 16.6: 热重载 ---");
+        ShowHotReloadConfiguration();
+
+        // 示例 7: 实际连接测试
+        Console.WriteLine("\n--- 示例 16.7: 连接测试 ---");
+        await TestConnectionAsync();
+
+        Console.WriteLine("\n示例 16 完成\n");
+    }
+
+    private static void ShowTokenAuthConfiguration()
+    {
+        Console.WriteLine("Token 认证配置:");
+        Console.WriteLine(@"
+// 使用 Action 配置
+var cfg = new CfgBuilder()
+    .AddVault(options =>
+    {
+        options.Address = ""http://localhost:8200"";  // Vault 地址
+        options.Token = ""your-vault-token"";         // Vault Token
+        options.EnginePath = ""secret"";              // KV 引擎路径
+        options.Path = ""myapp/config"";              // 密钥路径
+        options.KvVersion = 2;                        // KV 版本(1 或 2)
+    })
+    .Build();
+
+// 读取密钥
+var dbPassword = cfg.Get(""Database:Password"");
+var apiKey = cfg.Get(""ApiKey"");
+");
+    }
+
+    private static void ShowKvVersionConfiguration()
+    {
+        Console.WriteLine("KV V1 和 V2 引擎:");
+        Console.WriteLine(@"
+// KV V1 引擎(简化方法)
+var cfgV1 = new CfgBuilder()
+    .AddVaultV1(
+        address: ""http://localhost:8200"",
+        token: ""your-token"",
+        enginePath: ""kv"",
+        path: ""myapp/config"")
+    .Build();
+
+// KV V2 引擎(简化方法,推荐)
+var cfgV2 = new CfgBuilder()
+    .AddVaultV2(
+        address: ""http://localhost:8200"",
+        token: ""your-token"",
+        enginePath: ""secret"",
+        path: ""myapp/config"")
+    .Build();
+
+// KV V2 支持版本控制,可以查看密钥的历史版本
+// 在 Vault CLI 中:vault kv get -version=1 secret/myapp/config
+");
+    }
+
+    private static void ShowUserPassAuthConfiguration()
+    {
+        Console.WriteLine("UserPass 认证:");
+        Console.WriteLine(@"
+// 使用用户名密码认证
+var cfg = new CfgBuilder()
+    .AddVaultUserPass(
+        address: ""http://localhost:8200"",
+        username: ""myuser"",
+        password: ""mypassword"",
+        enginePath: ""secret"",
+        path: ""myapp/config"")
+    .Build();
+
+// 或使用 Action 配置
+var cfg2 = new CfgBuilder()
+    .AddVault(options =>
+    {
+        options.Address = ""http://localhost:8200"";
+        options.AuthMethod = VaultAuthMethod.UserPass;
+        options.Username = ""myuser"";
+        options.Password = ""mypassword"";
+        options.EnginePath = ""secret"";
+        options.Path = ""myapp/config"";
+    })
+    .Build();
+");
+    }
+
+    private static void ShowAppRoleAuthConfiguration()
+    {
+        Console.WriteLine("AppRole 认证(推荐用于生产环境):");
+        Console.WriteLine(@"
+// AppRole 是 Vault 推荐的机器认证方式
+var cfg = new CfgBuilder()
+    .AddVaultAppRole(
+        address: ""http://localhost:8200"",
+        roleId: ""your-role-id"",
+        roleSecret: ""your-role-secret"",
+        enginePath: ""secret"",
+        path: ""myapp/config"")
+    .Build();
+
+// 或使用 Action 配置
+var cfg2 = new CfgBuilder()
+    .AddVault(options =>
+    {
+        options.Address = ""http://localhost:8200"";
+        options.AuthMethod = VaultAuthMethod.AppRole;
+        options.RoleId = ""your-role-id"";
+        options.RoleSecret = ""your-role-secret"";
+        options.EnginePath = ""secret"";
+        options.Path = ""myapp/config"";
+    })
+    .Build();
+
+// 在 Vault 中创建 AppRole:
+// vault auth enable approle
+// vault write auth/approle/role/myapp policies=""myapp-policy""
+// vault read auth/approle/role/myapp/role-id
+// vault write -f auth/approle/role/myapp/secret-id
+");
+    }
+
+    private static void ShowNamespaceConfiguration()
+    {
+        Console.WriteLine("企业版命名空间配置:");
+        Console.WriteLine(@"
+// Vault Enterprise 支持命名空间隔离
+var cfg = new CfgBuilder()
+    .AddVault(options =>
+    {
+        options.Address = ""http://vault.example.com:8200"";
+        options.Token = ""your-token"";
+        options.Namespace = ""myteam"";           // 企业版命名空间
+        options.EnginePath = ""secret"";
+        options.Path = ""myapp/config"";
+    })
+    .Build();
+
+// 多层级配置(不同命名空间)
+var cfgMulti = new CfgBuilder()
+    .AddVault(options =>
+    {
+        options.Address = ""http://vault.example.com:8200"";
+        options.Token = ""your-token"";
+        options.Namespace = ""shared"";           // 共享命名空间
+        options.EnginePath = ""secret"";
+        options.Path = ""common/config"";
+    }, level: 0)
+    .AddVault(options =>
+    {
+        options.Address = ""http://vault.example.com:8200"";
+        options.Token = ""your-token"";
+        options.Namespace = ""myteam"";           // 团队命名空间
+        options.EnginePath = ""secret"";
+        options.Path = ""myapp/config"";
+    }, level: 1)
+    .Build();
+");
+    }
+
+    private static void ShowHotReloadConfiguration()
+    {
+        Console.WriteLine("热重载配置:");
+        Console.WriteLine(@"
+var cfg = new CfgBuilder()
+    .AddVault(options =>
+    {
+        options.Address = ""http://localhost:8200"";
+        options.Token = ""your-token"";
+        options.EnginePath = ""secret"";
+        options.Path = ""myapp/config"";
+        options.EnableHotReload = true;              // 启用热重载
+        options.PollInterval = TimeSpan.FromSeconds(30); // 轮询间隔
+        options.ReconnectInterval = TimeSpan.FromSeconds(5); // 重连间隔
+    })
+    .Build();
+
+// 订阅配置变更
+cfg.ConfigChanges.Subscribe(change =>
+{
+    Console.WriteLine($""密钥变更: {change.Key}"");
+    // 注意:出于安全考虑,不要打印密钥值
+});
+
+// 注意:Vault KV 引擎不支持原生 Watch,
+// Apq.Cfg.Vault 使用轮询方式检测变更
+");
+    }
+
+    private static async Task TestConnectionAsync()
+    {
+        Console.WriteLine("尝试连接本地 Vault(开发模式)...");
+        
+        try
+        {
+            var cfg = new CfgBuilder()
+                .AddVault(options =>
+                {
+                    options.Address = "http://localhost:8200";
+                    options.Token = "myroot";  // 开发模式默认 Token
+                    options.EnginePath = "secret";
+                    options.Path = "apq-cfg-demo";
+                    options.KvVersion = 2;
+                })
+                .Build();
+
+            // 尝试读取配置
+            var testValue = cfg.Get("test");
+            Console.WriteLine($"✓ 连接成功!test 键的值: {testValue ?? "(空)"}");
+            
+            // 显示所有键
+            var keys = cfg.GetChildKeys();
+            Console.WriteLine($"  配置键数量: {keys.Count()}");
+        }
+        catch (Exception ex)
+        {
+            Console.WriteLine($"✗ 连接失败: {ex.Message}");
+            Console.WriteLine("  提示: 请确保 Vault 服务正在运行");
+            Console.WriteLine("  快速启动(开发模式):");
+            Console.WriteLine("    docker run -d -p 8200:8200 -e VAULT_DEV_ROOT_TOKEN_ID=myroot vault");
+            Console.WriteLine("  访问 UI: http://localhost:8200 (Token: myroot)");
+        }
+        
+        await Task.CompletedTask;
+    }
+}

+ 213 - 0
Samples/Apq.Cfg.Samples/Demos/ZookeeperDemo.cs

@@ -0,0 +1,213 @@
+using Apq.Cfg;
+using Apq.Cfg.Zookeeper;
+
+namespace Apq.Cfg.Samples.Demos;
+
+/// <summary>
+/// 示例 15: Zookeeper 配置中心
+/// 演示如何使用 Zookeeper 作为配置源
+/// </summary>
+public static class ZookeeperDemo
+{
+    public static async Task RunAsync(string baseDir)
+    {
+        Console.WriteLine("═══════════════════════════════════════════════════════════════");
+        Console.WriteLine("示例 15: Zookeeper 配置中心");
+        Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
+
+        // 注意:此示例需要运行中的 Zookeeper 服务
+        // 可以使用 Docker 快速启动:docker run -d -p 2181:2181 zookeeper
+        
+        Console.WriteLine("【Zookeeper 配置源说明】");
+        Console.WriteLine("Zookeeper 是 Apache 开源的分布式协调服务,常用于配置管理。");
+        Console.WriteLine("Apq.Cfg.Zookeeper 支持从 Zookeeper 节点读取配置。\n");
+
+        // 示例 1: 基本配置
+        Console.WriteLine("--- 示例 15.1: 基本配置 ---");
+        ShowBasicConfiguration();
+
+        // 示例 2: 集群配置
+        Console.WriteLine("\n--- 示例 15.2: 集群配置 ---");
+        ShowClusterConfiguration();
+
+        // 示例 3: 认证配置
+        Console.WriteLine("\n--- 示例 15.3: 认证配置 ---");
+        ShowAuthConfiguration();
+
+        // 示例 4: JSON 格式
+        Console.WriteLine("\n--- 示例 15.4: JSON 格式 ---");
+        ShowJsonFormatConfiguration();
+
+        // 示例 5: 监听配置变更
+        Console.WriteLine("\n--- 示例 15.5: 监听配置变更 ---");
+        ShowWatchConfiguration();
+
+        // 示例 6: 实际连接测试
+        Console.WriteLine("\n--- 示例 15.6: 连接测试 ---");
+        await TestConnectionAsync();
+
+        Console.WriteLine("\n示例 15 完成\n");
+    }
+
+    private static void ShowBasicConfiguration()
+    {
+        Console.WriteLine("基本配置代码示例:");
+        Console.WriteLine(@"
+// 使用 Action 配置
+var cfg = new CfgBuilder()
+    .AddZookeeper(options =>
+    {
+        options.ConnectionString = ""localhost:2181"";  // Zookeeper 连接字符串
+        options.RootPath = ""/myapp/config"";           // 根路径
+    }, level: 0)
+    .Build();
+
+// 或使用简化方法
+var cfg2 = new CfgBuilder()
+    .AddZookeeper(""localhost:2181"", rootPath: ""/myapp/config"")
+    .Build();
+
+// 读取配置(假设 Zookeeper 中有 /myapp/config/Database/Host 节点)
+var host = cfg.Get(""Database:Host"");
+");
+    }
+
+    private static void ShowClusterConfiguration()
+    {
+        Console.WriteLine("集群配置(多节点):");
+        Console.WriteLine(@"
+// Zookeeper 集群通常有多个节点,配置多个地址可提高可用性
+var cfg = new CfgBuilder()
+    .AddZookeeper(options =>
+    {
+        // 多节点连接字符串,用逗号分隔
+        options.ConnectionString = ""zk1.example.com:2181,zk2.example.com:2181,zk3.example.com:2181"";
+        options.RootPath = ""/myapp/config"";
+        options.SessionTimeout = TimeSpan.FromSeconds(30);   // 会话超时
+        options.ConnectTimeout = TimeSpan.FromSeconds(10);   // 连接超时
+        options.ReconnectInterval = TimeSpan.FromSeconds(5); // 重连间隔
+    }, level: 0)
+    .Build();
+");
+    }
+
+    private static void ShowAuthConfiguration()
+    {
+        Console.WriteLine("认证配置:");
+        Console.WriteLine(@"
+// Zookeeper 支持 digest 认证方案
+var cfg = new CfgBuilder()
+    .AddZookeeper(options =>
+    {
+        options.ConnectionString = ""localhost:2181"";
+        options.RootPath = ""/myapp/config"";
+        options.AuthScheme = ""digest"";           // 认证方案
+        options.AuthInfo = ""user:password"";      // 认证信息
+    }, level: 0)
+    .Build();
+");
+    }
+
+    private static void ShowJsonFormatConfiguration()
+    {
+        Console.WriteLine("JSON 格式配置:");
+        Console.WriteLine(@"
+// 1. KeyValue 格式(默认)- 每个 ZNode 对应一个配置项
+var cfg1 = new CfgBuilder()
+    .AddZookeeper(options =>
+    {
+        options.ConnectionString = ""localhost:2181"";
+        options.RootPath = ""/myapp/config"";
+        options.DataFormat = ZookeeperDataFormat.KeyValue;
+    }, level: 0)
+    .Build();
+
+// 2. JSON 格式 - 单个节点存储 JSON 配置
+var cfg2 = new CfgBuilder()
+    .AddZookeeper(options =>
+    {
+        options.ConnectionString = ""localhost:2181"";
+        options.RootPath = ""/myapp"";
+        options.DataFormat = ZookeeperDataFormat.Json;
+        options.SingleNode = ""config"";  // 读取 /myapp/config 节点的 JSON 内容
+    }, level: 0)
+    .Build();
+
+// 或使用简化方法
+var cfg3 = new CfgBuilder()
+    .AddZookeeperJson(""localhost:2181"", nodePath: ""/myapp/config.json"")
+    .Build();
+");
+    }
+
+    private static void ShowWatchConfiguration()
+    {
+        Console.WriteLine("监听配置变更:");
+        Console.WriteLine(@"
+var cfg = new CfgBuilder()
+    .AddZookeeper(options =>
+    {
+        options.ConnectionString = ""localhost:2181"";
+        options.RootPath = ""/myapp/config"";
+        options.EnableHotReload = true;  // 启用热重载(默认 true)
+    }, level: 0)
+    .Build();
+
+// 订阅配置变更(使用 Zookeeper Watch 机制)
+cfg.ConfigChanges.Subscribe(change =>
+{
+    Console.WriteLine($""配置变更: {change.Key}"");
+    Console.WriteLine($""  旧值: {change.OldValue}"");
+    Console.WriteLine($""  新值: {change.NewValue}"");
+    Console.WriteLine($""  类型: {change.ChangeType}"");
+});
+
+// 多层级配置覆盖
+var cfgMulti = new CfgBuilder()
+    .AddZookeeper(options =>
+    {
+        options.ConnectionString = ""localhost:2181"";
+        options.RootPath = ""/shared/config"";  // 公共配置
+    }, level: 0)
+    .AddZookeeper(options =>
+    {
+        options.ConnectionString = ""localhost:2181"";
+        options.RootPath = ""/myapp/config"";   // 应用配置(覆盖公共配置)
+    }, level: 1)
+    .Build();
+");
+    }
+
+    private static async Task TestConnectionAsync()
+    {
+        Console.WriteLine("尝试连接本地 Zookeeper...");
+        
+        try
+        {
+            var cfg = new CfgBuilder()
+                .AddZookeeper(options =>
+                {
+                    options.ConnectionString = "localhost:2181";
+                    options.RootPath = "/apq-cfg-demo";
+                    options.ConnectTimeout = TimeSpan.FromSeconds(3);
+                }, level: 0)
+                .Build();
+
+            // 尝试读取配置
+            var testValue = cfg.Get("test");
+            Console.WriteLine($"✓ 连接成功!test 键的值: {testValue ?? "(空)"}");
+            
+            // 显示所有键
+            var keys = cfg.GetChildKeys();
+            Console.WriteLine($"  配置键数量: {keys.Count()}");
+        }
+        catch (Exception ex)
+        {
+            Console.WriteLine($"✗ 连接失败: {ex.Message}");
+            Console.WriteLine("  提示: 请确保 Zookeeper 服务正在运行");
+            Console.WriteLine("  快速启动: docker run -d -p 2181:2181 zookeeper");
+        }
+        
+        await Task.CompletedTask;
+    }
+}

+ 31 - 0
Samples/Apq.Cfg.Samples/Models/ConfigModels.cs

@@ -0,0 +1,31 @@
+namespace Apq.Cfg.Samples.Models;
+
+/// <summary>
+/// 数据库配置选项
+/// </summary>
+public class DatabaseOptions
+{
+    public string? Host { get; set; }
+    public int Port { get; set; }
+    public string? Name { get; set; }
+}
+
+/// <summary>
+/// 日志配置选项
+/// </summary>
+public class LoggingOptions
+{
+    public string? Level { get; set; }
+    public bool EnableConsole { get; set; }
+}
+
+/// <summary>
+/// 用于类型转换示例的日志级别枚举
+/// </summary>
+public enum LogLevel
+{
+    Debug,
+    Info,
+    Warning,
+    Error
+}

+ 21 - 637
Samples/Apq.Cfg.Samples/Program.cs

@@ -1,14 +1,4 @@
-using System.Text;
-using Apq.Cfg;
-using Apq.Cfg.Changes;
-using Apq.Cfg.Ini;
-using Apq.Cfg.Xml;
-using Apq.Cfg.Yaml;
-using Apq.Cfg.Toml;
-using Microsoft.Extensions.Configuration;
-using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.Options;
-using Microsoft.Extensions.Primitives;
+using Apq.Cfg.Samples.Demos;
 
 Console.WriteLine("╔══════════════════════════════════════════════════════════════╗");
 Console.WriteLine("║              Apq.Cfg 完整功能示例                            ║");
@@ -16,633 +6,27 @@ Console.WriteLine("╚═══════════════════
 
 var baseDir = AppContext.BaseDirectory;
 
-// ============================================================================
-// 示例 1: 基础用法 - JSON 配置与层级覆盖
-// ============================================================================
-await Demo1_BasicUsage(baseDir);
-
-// ============================================================================
-// 示例 2: 多格式支持 - INI、XML、YAML、TOML
-// ============================================================================
-await Demo2_MultiFormat(baseDir);
-
-// ============================================================================
-// 示例 3: 配置节 (GetSection) 与子键枚举
-// ============================================================================
-await Demo3_ConfigSection(baseDir);
-
-// ============================================================================
-// 示例 4: 批量操作 - GetMany / SetMany
-// ============================================================================
-await Demo4_BatchOperations(baseDir);
-
-// ============================================================================
-// 示例 5: 类型转换
-// ============================================================================
-await Demo5_TypeConversion(baseDir);
-
-// ============================================================================
-// 示例 6: 动态配置重载
-// ============================================================================
-await Demo6_DynamicReload(baseDir);
-
-// ============================================================================
-// 示例 7: 依赖注入集成
-// ============================================================================
-await Demo7_DependencyInjection(baseDir);
-
-// ============================================================================
-// 示例 8: 编码映射配置
-// ============================================================================
-await Demo8_EncodingMapping(baseDir);
+// 基础示例 (1-8)
+await BasicUsageDemo.RunAsync(baseDir);
+await MultiFormatDemo.RunAsync(baseDir);
+await ConfigSectionDemo.RunAsync(baseDir);
+await BatchOperationsDemo.RunAsync(baseDir);
+await TypeConversionDemo.RunAsync(baseDir);
+await DynamicReloadDemo.RunAsync(baseDir);
+await DependencyInjectionDemo.RunAsync(baseDir);
+await EncodingMappingDemo.RunAsync(baseDir);
+
+// 扩展项目示例 (9-17)
+await RedisDemo.RunAsync(baseDir);
+await DatabaseDemo.RunAsync(baseDir);
+await ConsulDemo.RunAsync(baseDir);
+await EtcdDemo.RunAsync(baseDir);
+await NacosDemo.RunAsync(baseDir);
+await ApolloDemo.RunAsync(baseDir);
+await ZookeeperDemo.RunAsync(baseDir);
+await VaultDemo.RunAsync(baseDir);
+await SourceGeneratorDemo.RunAsync(baseDir);
 
 Console.WriteLine("\n╔══════════════════════════════════════════════════════════════╗");
 Console.WriteLine("║              所有示例执行完成                                ║");
 Console.WriteLine("╚══════════════════════════════════════════════════════════════╝");
-
-// ============================================================================
-// 示例实现
-// ============================================================================
-
-static async Task Demo1_BasicUsage(string baseDir)
-{
-    Console.WriteLine("═══════════════════════════════════════════════════════════════");
-    Console.WriteLine("示例 1: 基础用法 - JSON 配置与层级覆盖");
-    Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
-
-    var configPath = Path.Combine(baseDir, "config.json");
-    var localConfigPath = Path.Combine(baseDir, "config.local.json");
-
-    // 创建基础配置
-    File.WriteAllText(configPath, """
-    {
-        "App": {
-            "Name": "MyApp",
-            "Version": "1.0.0",
-            "Debug": false
-        },
-        "Database": {
-            "Host": "localhost",
-            "Port": 3306,
-            "Name": "mydb"
-        }
-    }
-    """);
-
-    // 创建本地覆盖配置(高优先级)
-    File.WriteAllText(localConfigPath, """
-    {
-        "App": {
-            "Debug": true
-        },
-        "Database": {
-            "Host": "192.168.1.100"
-        }
-    }
-    """);
-
-    // 构建配置:level 越大优先级越高
-    // 注意:环境变量不可写,所以 isPrimaryWriter 设置在 JSON 配置源上
-    var cfg = new CfgBuilder()
-        .AddJson(configPath, level: 0, writeable: false)
-        .AddJson(localConfigPath, level: 1, writeable: true, isPrimaryWriter: true)
-        .AddEnvironmentVariables(level: 2, prefix: "MYAPP_")
-        .Build();
-
-    // 读取配置
-    Console.WriteLine("1.1 读取配置值:");
-    Console.WriteLine($"    App:Name = {cfg.Get("App:Name")}");
-    Console.WriteLine($"    App:Version = {cfg.Get("App:Version")}");
-    Console.WriteLine($"    App:Debug = {cfg.Get("App:Debug")} (被本地配置覆盖为 true)");
-    Console.WriteLine($"    Database:Host = {cfg.Get("Database:Host")} (被本地配置覆盖)");
-    Console.WriteLine($"    Database:Port = {cfg.Get("Database:Port")}");
-
-    // 检查配置是否存在
-    Console.WriteLine("\n1.2 检查配置是否存在:");
-    Console.WriteLine($"    Exists(App:Name) = {cfg.Exists("App:Name")}");
-    Console.WriteLine($"    Exists(NotExist:Key) = {cfg.Exists("NotExist:Key")}");
-
-    // 修改配置(写入到 isPrimaryWriter 的配置源,需要指定 targetLevel)
-    Console.WriteLine("\n1.3 修改配置:");
-    cfg.Set("App:LastRun", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), targetLevel: 1);
-    await cfg.SaveAsync(targetLevel: 1);
-    Console.WriteLine($"    已设置 App:LastRun = {cfg.Get("App:LastRun")}");
-
-    // 删除配置
-    Console.WriteLine("\n1.4 删除配置:");
-    cfg.Set("App:TempKey", "临时值", targetLevel: 1);
-    Console.WriteLine($"    设置 App:TempKey = {cfg.Get("App:TempKey")}");
-    cfg.Remove("App:TempKey", targetLevel: 1);
-    await cfg.SaveAsync(targetLevel: 1);
-    Console.WriteLine($"    删除后 App:TempKey = {cfg.Get("App:TempKey") ?? "(null)"}");
-
-    // 转换为 Microsoft.Extensions.Configuration
-    Console.WriteLine("\n1.5 转换为 IConfigurationRoot:");
-    var msConfig = cfg.ToMicrosoftConfiguration();
-    Console.WriteLine($"    msConfig[\"App:Name\"] = {msConfig["App:Name"]}");
-
-    cfg.Dispose();
-    File.Delete(configPath);
-    File.Delete(localConfigPath);
-
-    Console.WriteLine("\n[示例 1 完成]\n");
-}
-
-static async Task Demo2_MultiFormat(string baseDir)
-{
-    Console.WriteLine("═══════════════════════════════════════════════════════════════");
-    Console.WriteLine("示例 2: 多格式支持 - INI、XML、YAML、TOML");
-    Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
-
-    // INI 格式
-    var iniPath = Path.Combine(baseDir, "config.ini");
-    File.WriteAllText(iniPath, """
-    [App]
-    Name=IniApp
-    Version=2.0.0
-
-    [Database]
-    Host=ini-server
-    Port=5432
-    """);
-
-    // XML 格式
-    var xmlPath = Path.Combine(baseDir, "config.xml");
-    File.WriteAllText(xmlPath, """
-    <?xml version="1.0" encoding="utf-8"?>
-    <configuration>
-        <App>
-            <Name>XmlApp</Name>
-            <Version>3.0.0</Version>
-        </App>
-        <Database>
-            <Host>xml-server</Host>
-            <Port>1433</Port>
-        </Database>
-    </configuration>
-    """);
-
-    // YAML 格式
-    var yamlPath = Path.Combine(baseDir, "config.yaml");
-    File.WriteAllText(yamlPath, """
-    App:
-      Name: YamlApp
-      Version: 4.0.0
-    Database:
-      Host: yaml-server
-      Port: 27017
-    """);
-
-    // TOML 格式
-    var tomlPath = Path.Combine(baseDir, "config.toml");
-    File.WriteAllText(tomlPath, """
-    [App]
-    Name = "TomlApp"
-    Version = "5.0.0"
-
-    [Database]
-    Host = "toml-server"
-    Port = 6379
-    """);
-
-    // 分别测试各格式
-    Console.WriteLine("2.1 INI 格式:");
-    using (var iniCfg = new CfgBuilder().AddIni(iniPath, level: 0, writeable: true).Build())
-    {
-        Console.WriteLine($"    App:Name = {iniCfg.Get("App:Name")}");
-        Console.WriteLine($"    Database:Port = {iniCfg.Get("Database:Port")}");
-    }
-
-    Console.WriteLine("\n2.2 XML 格式:");
-    using (var xmlCfg = new CfgBuilder().AddXml(xmlPath, level: 0, writeable: true).Build())
-    {
-        Console.WriteLine($"    App:Name = {xmlCfg.Get("App:Name")}");
-        Console.WriteLine($"    Database:Port = {xmlCfg.Get("Database:Port")}");
-    }
-
-    Console.WriteLine("\n2.3 YAML 格式:");
-    using (var yamlCfg = new CfgBuilder().AddYaml(yamlPath, level: 0, writeable: true).Build())
-    {
-        Console.WriteLine($"    App:Name = {yamlCfg.Get("App:Name")}");
-        Console.WriteLine($"    Database:Port = {yamlCfg.Get("Database:Port")}");
-    }
-
-    Console.WriteLine("\n2.4 TOML 格式:");
-    using (var tomlCfg = new CfgBuilder().AddToml(tomlPath, level: 0, writeable: true).Build())
-    {
-        Console.WriteLine($"    App:Name = {tomlCfg.Get("App:Name")}");
-        Console.WriteLine($"    Database:Port = {tomlCfg.Get("Database:Port")}");
-    }
-
-    // 混合多种格式
-    Console.WriteLine("\n2.5 混合多种格式(层级覆盖):");
-    using var mixedCfg = new CfgBuilder()
-        .AddIni(iniPath, level: 0, writeable: false)
-        .AddYaml(yamlPath, level: 1, writeable: false)
-        .AddToml(tomlPath, level: 2, writeable: true, isPrimaryWriter: true)
-        .Build();
-
-    Console.WriteLine($"    App:Name = {mixedCfg.Get("App:Name")} (来自 TOML,最高优先级)");
-    Console.WriteLine($"    App:Version = {mixedCfg.Get("App:Version")} (来自 TOML)");
-
-    File.Delete(iniPath);
-    File.Delete(xmlPath);
-    File.Delete(yamlPath);
-    File.Delete(tomlPath);
-
-    Console.WriteLine("\n[示例 2 完成]\n");
-    await Task.CompletedTask;
-}
-
-static async Task Demo3_ConfigSection(string baseDir)
-{
-    Console.WriteLine("═══════════════════════════════════════════════════════════════");
-    Console.WriteLine("示例 3: 配置节 (GetSection) 与子键枚举");
-    Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
-
-    var configPath = Path.Combine(baseDir, "section-demo.json");
-    File.WriteAllText(configPath, """
-    {
-        "Database": {
-            "Primary": {
-                "Host": "primary.db.local",
-                "Port": 3306,
-                "Username": "admin"
-            },
-            "Replica": {
-                "Host": "replica.db.local",
-                "Port": 3307,
-                "Username": "reader"
-            }
-        },
-        "Cache": {
-            "Redis": {
-                "Host": "redis.local",
-                "Port": 6379
-            }
-        }
-    }
-    """);
-
-    using var cfg = new CfgBuilder()
-        .AddJson(configPath, level: 0, writeable: true, isPrimaryWriter: true)
-        .Build();
-
-    // 获取配置节
-    Console.WriteLine("3.1 使用 GetSection 简化嵌套访问:");
-    var dbSection = cfg.GetSection("Database");
-    var primarySection = dbSection.GetSection("Primary");
-
-    Console.WriteLine($"    Database:Primary:Host = {primarySection.Get("Host")}");
-    Console.WriteLine($"    Database:Primary:Port = {primarySection.Get<int>("Port")}");
-
-    // 枚举子键
-    Console.WriteLine("\n3.2 枚举配置节的子键:");
-    Console.WriteLine("    Database 的子键:");
-    foreach (var key in dbSection.GetChildKeys())
-    {
-        Console.WriteLine($"      - {key}");
-    }
-
-    Console.WriteLine("\n    顶级配置键:");
-    foreach (var key in cfg.GetChildKeys())
-    {
-        Console.WriteLine($"      - {key}");
-    }
-
-    // 通过配置节修改值
-    Console.WriteLine("\n3.3 通过配置节修改值:");
-    var replicaSection = dbSection.GetSection("Replica");
-    replicaSection.Set("Port", "3308");
-    await cfg.SaveAsync();
-    Console.WriteLine($"    修改后 Database:Replica:Port = {replicaSection.Get("Port")}");
-
-    File.Delete(configPath);
-
-    Console.WriteLine("\n[示例 3 完成]\n");
-}
-
-static async Task Demo4_BatchOperations(string baseDir)
-{
-    Console.WriteLine("═══════════════════════════════════════════════════════════════");
-    Console.WriteLine("示例 4: 批量操作 - GetMany / SetMany");
-    Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
-
-    var configPath = Path.Combine(baseDir, "batch-demo.json");
-    File.WriteAllText(configPath, """
-    {
-        "Settings": {
-            "Theme": "dark",
-            "Language": "zh-CN",
-            "FontSize": "14",
-            "AutoSave": "true"
-        }
-    }
-    """);
-
-    using var cfg = new CfgBuilder()
-        .AddJson(configPath, level: 0, writeable: true, isPrimaryWriter: true)
-        .Build();
-
-    // 批量获取
-    Console.WriteLine("4.1 批量获取 (GetMany):");
-    var keys = new[] { "Settings:Theme", "Settings:Language", "Settings:FontSize" };
-    var values = cfg.GetMany(keys);
-    foreach (var kv in values)
-    {
-        Console.WriteLine($"    {kv.Key} = {kv.Value}");
-    }
-
-    // 批量获取并转换类型
-    Console.WriteLine("\n4.2 批量获取并转换类型 (GetMany<T>):");
-    var intKeys = new[] { "Settings:FontSize" };
-    var intValues = cfg.GetMany<int>(intKeys);
-    foreach (var kv in intValues)
-    {
-        Console.WriteLine($"    {kv.Key} = {kv.Value} (int)");
-    }
-
-    // 批量设置
-    Console.WriteLine("\n4.3 批量设置 (SetMany):");
-    var newValues = new Dictionary<string, string?>
-    {
-        ["Settings:Theme"] = "light",
-        ["Settings:FontSize"] = "16",
-        ["Settings:NewOption"] = "enabled"
-    };
-    cfg.SetMany(newValues);
-    await cfg.SaveAsync();
-
-    Console.WriteLine("    批量设置后的值:");
-    var updatedValues = cfg.GetMany(new[] { "Settings:Theme", "Settings:FontSize", "Settings:NewOption" });
-    foreach (var kv in updatedValues)
-    {
-        Console.WriteLine($"    {kv.Key} = {kv.Value}");
-    }
-
-    File.Delete(configPath);
-
-    Console.WriteLine("\n[示例 4 完成]\n");
-}
-
-static async Task Demo5_TypeConversion(string baseDir)
-{
-    Console.WriteLine("═══════════════════════════════════════════════════════════════");
-    Console.WriteLine("示例 5: 类型转换");
-    Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
-
-    var configPath = Path.Combine(baseDir, "types-demo.json");
-    File.WriteAllText(configPath, """
-    {
-        "Types": {
-            "IntValue": "42",
-            "LongValue": "9223372036854775807",
-            "DoubleValue": "3.14159",
-            "DecimalValue": "123.456",
-            "BoolTrue": "true",
-            "BoolFalse": "false",
-            "DateValue": "2024-12-25",
-            "GuidValue": "550e8400-e29b-41d4-a716-446655440000",
-            "EnumValue": "Warning"
-        }
-    }
-    """);
-
-    using var cfg = new CfgBuilder()
-        .AddJson(configPath, level: 0, writeable: false)
-        .Build();
-
-    Console.WriteLine("5.1 各种类型转换:");
-    Console.WriteLine($"    int: {cfg.Get<int>("Types:IntValue")}");
-    Console.WriteLine($"    long: {cfg.Get<long>("Types:LongValue")}");
-    Console.WriteLine($"    double: {cfg.Get<double>("Types:DoubleValue")}");
-    Console.WriteLine($"    decimal: {cfg.Get<decimal>("Types:DecimalValue")}");
-    Console.WriteLine($"    bool (true): {cfg.Get<bool>("Types:BoolTrue")}");
-    Console.WriteLine($"    bool (false): {cfg.Get<bool>("Types:BoolFalse")}");
-    Console.WriteLine($"    DateTime: {cfg.Get<DateTime>("Types:DateValue"):yyyy-MM-dd}");
-    Console.WriteLine($"    Guid: {cfg.Get<Guid>("Types:GuidValue")}");
-    Console.WriteLine($"    Enum: {cfg.Get<LogLevel>("Types:EnumValue")}");
-
-    Console.WriteLine("\n5.2 可空类型与默认值:");
-    Console.WriteLine($"    不存在的键 (int?): {cfg.Get<int?>("Types:NotExist") ?? -1}");
-    Console.WriteLine($"    不存在的键 (string): {cfg.Get("Types:NotExist") ?? "(null)"}");
-
-    File.Delete(configPath);
-
-    Console.WriteLine("\n[示例 5 完成]\n");
-    await Task.CompletedTask;
-}
-
-static async Task Demo6_DynamicReload(string baseDir)
-{
-    Console.WriteLine("═══════════════════════════════════════════════════════════════");
-    Console.WriteLine("示例 6: 动态配置重载");
-    Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
-
-    var configPath = Path.Combine(baseDir, "reload-demo.json");
-    File.WriteAllText(configPath, """
-    {
-        "App": {
-            "RefreshInterval": "30"
-        }
-    }
-    """);
-
-    // 启用 reloadOnChange
-    var cfg = new CfgBuilder()
-        .AddJson(configPath, level: 0, writeable: true, isPrimaryWriter: true, reloadOnChange: true)
-        .Build();
-
-    Console.WriteLine("6.1 配置动态重载选项:");
-    var msConfig = cfg.ToMicrosoftConfiguration(new DynamicReloadOptions
-    {
-        DebounceMs = 100,                    // 防抖时间
-        EnableDynamicReload = true,          // 启用动态重载
-        Strategy = ReloadStrategy.Eager,     // 立即重载
-        RollbackOnError = true,              // 错误时回滚
-        HistorySize = 5                      // 保留 5 条历史
-    });
-    Console.WriteLine("    已配置: DebounceMs=100, Strategy=Eager, HistorySize=5");
-
-    // 使用 IChangeToken 监听变更
-    Console.WriteLine("\n6.2 使用 IChangeToken 监听变更:");
-    var changeCount = 0;
-    ChangeToken.OnChange(
-        () => msConfig.GetReloadToken(),
-        () =>
-        {
-            changeCount++;
-            Console.WriteLine($"    [IChangeToken] 配置已更新 (第 {changeCount} 次)");
-        });
-    Console.WriteLine("    已注册 IChangeToken 回调");
-
-    // 使用 Rx 订阅配置变更
-    Console.WriteLine("\n6.3 使用 Rx 订阅配置变更:");
-    using var subscription = cfg.ConfigChanges.Subscribe(e =>
-    {
-        Console.WriteLine($"    [Rx] 批次 {e.BatchId} - {e.Changes.Count} 个变更:");
-        foreach (var (key, change) in e.Changes)
-        {
-            Console.WriteLine($"         [{change.Type}] {key}: {change.OldValue} -> {change.NewValue}");
-        }
-    });
-    Console.WriteLine("    已订阅 ConfigChanges");
-
-    // 模拟配置变更
-    Console.WriteLine("\n6.4 模拟配置变更:");
-    Console.WriteLine("    修改 App:RefreshInterval 为 60...");
-    cfg.Set("App:RefreshInterval", "60");
-    await cfg.SaveAsync();
-
-    // 等待变更通知
-    await Task.Delay(200);
-
-    Console.WriteLine($"\n    当前值: App:RefreshInterval = {cfg.Get("App:RefreshInterval")}");
-
-    cfg.Dispose();
-    File.Delete(configPath);
-
-    Console.WriteLine("\n[示例 6 完成]\n");
-}
-
-static async Task Demo7_DependencyInjection(string baseDir)
-{
-    Console.WriteLine("═══════════════════════════════════════════════════════════════");
-    Console.WriteLine("示例 7: 依赖注入集成");
-    Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
-
-    var configPath = Path.Combine(baseDir, "di-demo.json");
-    File.WriteAllText(configPath, """
-    {
-        "Database": {
-            "Host": "db.example.com",
-            "Port": "5432",
-            "Name": "production"
-        },
-        "Logging": {
-            "Level": "Information",
-            "EnableConsole": "true"
-        }
-    }
-    """);
-
-    // 配置服务容器
-    var services = new ServiceCollection();
-
-    // 方式1: 使用 AddApqCfg 注册配置
-    Console.WriteLine("7.1 注册 Apq.Cfg 到 DI 容器:");
-    services.AddApqCfg(cfg => cfg
-        .AddJson(configPath, level: 0, writeable: true, isPrimaryWriter: true));
-    Console.WriteLine("    已注册 ICfgRoot 和 IConfigurationRoot");
-
-    // 方式2: 绑定强类型配置
-    Console.WriteLine("\n7.2 绑定强类型配置:");
-    services.ConfigureApqCfg<DatabaseOptions>("Database");
-    services.ConfigureApqCfg<LoggingOptions>("Logging");
-    Console.WriteLine("    已绑定 DatabaseOptions 和 LoggingOptions");
-
-    // 构建服务提供者
-    var provider = services.BuildServiceProvider();
-
-    // 获取服务
-    Console.WriteLine("\n7.3 从 DI 容器获取服务:");
-    var cfgRoot = provider.GetRequiredService<ICfgRoot>();
-    var msConfig = provider.GetRequiredService<IConfigurationRoot>();
-    var dbOptions = provider.GetRequiredService<IOptions<DatabaseOptions>>().Value;
-    var logOptions = provider.GetRequiredService<IOptions<LoggingOptions>>().Value;
-
-    Console.WriteLine($"    ICfgRoot: Database:Host = {cfgRoot.Get("Database:Host")}");
-    Console.WriteLine($"    IConfigurationRoot: Database:Host = {msConfig["Database:Host"]}");
-    Console.WriteLine($"    DatabaseOptions: Host={dbOptions.Host}, Port={dbOptions.Port}, Name={dbOptions.Name}");
-    Console.WriteLine($"    LoggingOptions: Level={logOptions.Level}, EnableConsole={logOptions.EnableConsole}");
-
-    // 清理
-    if (provider is IDisposable disposable)
-        disposable.Dispose();
-    File.Delete(configPath);
-
-    Console.WriteLine("\n[示例 7 完成]\n");
-    await Task.CompletedTask;
-}
-
-static async Task Demo8_EncodingMapping(string baseDir)
-{
-    Console.WriteLine("═══════════════════════════════════════════════════════════════");
-    Console.WriteLine("示例 8: 编码映射配置");
-    Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
-
-    var configPath = Path.Combine(baseDir, "encoding-demo.json");
-    File.WriteAllText(configPath, """
-    {
-        "App": {
-            "Name": "编码测试应用",
-            "Description": "支持中文和特殊字符: äöü ñ 日本語"
-        }
-    }
-    """, Encoding.UTF8);
-
-    Console.WriteLine("8.1 编码检测置信度阈值:");
-    var cfg1 = new CfgBuilder()
-        .WithEncodingConfidenceThreshold(0.7f)
-        .AddJson(configPath, level: 0, writeable: false)
-        .Build();
-    Console.WriteLine($"    置信度阈值设置为 0.7");
-    Console.WriteLine($"    App:Name = {cfg1.Get("App:Name")}");
-    cfg1.Dispose();
-
-    Console.WriteLine("\n8.2 编码检测日志:");
-    var cfg2 = new CfgBuilder()
-        .WithEncodingDetectionLogging(result =>
-        {
-            Console.WriteLine($"    [编码检测] 文件: {Path.GetFileName(result.FilePath)}");
-            Console.WriteLine($"               编码: {result.Encoding.EncodingName}");
-            Console.WriteLine($"               置信度: {result.Confidence:P0}");
-            Console.WriteLine($"               方法: {result.Method}");
-        })
-        .AddJson(configPath, level: 0, writeable: false)
-        .Build();
-    cfg2.Dispose();
-
-    Console.WriteLine("\n8.3 编码映射规则:");
-    Console.WriteLine("    支持三种映射方式:");
-    Console.WriteLine("    - 完整路径: AddReadEncodingMapping(path, encoding)");
-    Console.WriteLine("    - 通配符:   AddReadEncodingMappingWildcard(\"*.json\", encoding)");
-    Console.WriteLine("    - 正则:     AddReadEncodingMappingRegex(@\"config.*\\.json$\", encoding)");
-
-    // 演示编码映射配置
-    var cfg3 = new CfgBuilder()
-        // 为特定文件指定编码
-        .AddReadEncodingMapping(configPath, Encoding.UTF8, priority: 100)
-        // 为所有 JSON 文件指定写入编码
-        .AddWriteEncodingMappingWildcard("*.json", new UTF8Encoding(false), priority: 50)
-        .AddJson(configPath, level: 0, writeable: false)
-        .Build();
-    Console.WriteLine("\n    已配置编码映射规则");
-    Console.WriteLine($"    App:Description = {cfg3.Get("App:Description")}");
-    cfg3.Dispose();
-
-    File.Delete(configPath);
-
-    Console.WriteLine("\n[示例 8 完成]\n");
-    await Task.CompletedTask;
-}
-
-// ============================================================================
-// 强类型配置类
-// ============================================================================
-
-public class DatabaseOptions
-{
-    public string? Host { get; set; }
-    public int Port { get; set; }
-    public string? Name { get; set; }
-}
-
-public class LoggingOptions
-{
-    public string? Level { get; set; }
-    public bool EnableConsole { get; set; }
-}
-
-// 用于类型转换示例的枚举
-public enum LogLevel { Debug, Info, Warning, Error }

+ 198 - 168
Samples/Apq.Cfg.Samples/README.md

@@ -1,215 +1,245 @@
-# Apq.Cfg.Samples - 功能示例
+# Apq.Cfg.Samples
 
-本示例项目演示了 Apq.Cfg 配置库的完整功能,包含 8 个独立的示例,覆盖所有主要特性。
+Apq.Cfg 配置库的完整功能示例项目。
+
+## 项目结构
+
+```
+Apq.Cfg.Samples/
+├── Program.cs                          # 入口程序,运行所有示例
+├── Models/
+│   └── ConfigModels.cs                 # 强类型配置模型
+└── Demos/
+    ├── BasicUsageDemo.cs               # 示例 1: 基础用法
+    ├── MultiFormatDemo.cs              # 示例 2: 多格式支持
+    ├── ConfigSectionDemo.cs            # 示例 3: 配置节访问
+    ├── BatchOperationsDemo.cs          # 示例 4: 批量操作
+    ├── TypeConversionDemo.cs           # 示例 5: 类型转换
+    ├── DynamicReloadDemo.cs            # 示例 6: 动态重载
+    ├── DependencyInjectionDemo.cs      # 示例 7: 依赖注入
+    ├── EncodingMappingDemo.cs          # 示例 8: 编码映射
+    ├── RedisDemo.cs                    # 示例 9: Redis 配置源
+    ├── DatabaseDemo.cs                 # 示例 10: 数据库配置源
+    ├── ConsulDemo.cs                   # 示例 11: Consul 配置源
+    ├── EtcdDemo.cs                     # 示例 12: Etcd 配置源
+    ├── NacosDemo.cs                    # 示例 13: Nacos 配置源
+    ├── ApolloDemo.cs                   # 示例 14: Apollo 配置源
+    ├── ZookeeperDemo.cs                # 示例 15: Zookeeper 配置源
+    ├── VaultDemo.cs                    # 示例 16: HashiCorp Vault 配置源
+    └── SourceGeneratorDemo.cs          # 示例 17: 源代码生成器
+```
 
 ## 运行示例
 
 ```bash
+# 在项目根目录运行
+dotnet run --project Samples/Apq.Cfg.Samples
+
+# 或进入示例目录运行
 cd Samples/Apq.Cfg.Samples
 dotnet run
 ```
 
-## 功能覆盖
+## 示例说明
 
-| 示例 | 功能模块 | 覆盖的 API |
-|------|----------|-----------|
-| 示例 1 | 基础用法 | `CfgBuilder`, `AddJson`, `AddEnvironmentVariables`, `Get`, `Set`, `Remove`, `Exists`, `SaveAsync`, `ToMicrosoftConfiguration` |
-| 示例 2 | 多格式支持 | `AddIni`, `AddXml`, `AddYaml`, `AddToml`, 混合格式层级覆盖 |
-| 示例 3 | 配置节 | `GetSection`, `GetChildKeys`, 嵌套配置访问 |
-| 示例 4 | 批量操作 | `GetMany`, `GetMany<T>`, `SetMany` |
-| 示例 5 | 类型转换 | `Get<T>` 支持 int, long, double, decimal, bool, DateTime, Guid, Enum |
-| 示例 6 | 动态重载 | `DynamicReloadOptions`, `IChangeToken`, `ConfigChanges` (Rx) |
-| 示例 7 | 依赖注入 | `AddApqCfg`, `ConfigureApqCfg<T>`, `IOptions<T>` |
-| 示例 8 | 编码映射 | `WithEncodingConfidenceThreshold`, `WithEncodingDetectionLogging`, `AddReadEncodingMapping`, `AddWriteEncodingMappingWildcard` |
+### 示例 1: 基础用法 (BasicUsageDemo)
 
-## 示例详情
+演示 Apq.Cfg 的基本功能:
+- JSON 配置文件加载
+- 多层级配置覆盖(level 参数)
+- 环境变量配置源
+- 配置读取、写入、删除
+- 转换为 Microsoft.Extensions.Configuration
 
-### 示例 1: 基础用法 - JSON 配置与层级覆盖
+### 示例 2: 多格式支持 (MultiFormatDemo)
 
-演示核心功能:
-- 创建多层级配置(基础配置 + 本地覆盖配置 + 环境变量)
-- `level` 参数控制优先级(数值越大优先级越高)
-- `writeable` 参数控制配置源是否可写
-- `isPrimaryWriter` 指定默认写入目标
-- `targetLevel` 参数指定写入到特定层级
+演示不同配置文件格式的支持
+- INI 格式 (`Apq.Cfg.Ini`)
+- XML 格式 (`Apq.Cfg.Xml`)
+- YAML 格式 (`Apq.Cfg.Yaml`)
+- TOML 格式 (`Apq.Cfg.Toml`)
+- 混合多种格式的层级覆盖
 
-```csharp
-var cfg = new CfgBuilder()
-    .AddJson(configPath, level: 0, writeable: false)
-    .AddJson(localConfigPath, level: 1, writeable: true, isPrimaryWriter: true)
-    .AddEnvironmentVariables(level: 2, prefix: "MYAPP_")
-    .Build();
-
-// 读取(自动从最高优先级获取)
-var value = cfg.Get("App:Name");
-
-// 写入(需指定 targetLevel,因为最高层级环境变量不可写)
-cfg.Set("App:LastRun", DateTime.Now.ToString(), targetLevel: 1);
-await cfg.SaveAsync(targetLevel: 1);
-```
+### 示例 3: 配置节访问 (ConfigSectionDemo)
 
-### 示例 2: 多格式支持
+演示配置节(GetSection)功能:
+- 使用 `GetSection` 简化嵌套配置访问
+- 枚举配置节的子键 (`GetChildKeys`)
+- 通过配置节修改值
 
-支持的配置格式:
-- **JSON** - 内置支持
-- **INI** - 需引用 `Apq.Cfg.Ini`
-- **XML** - 需引用 `Apq.Cfg.Xml`
-- **YAML** - 需引用 `Apq.Cfg.Yaml`
-- **TOML** - 需引用 `Apq.Cfg.Toml`
+### 示例 4: 批量操作 (BatchOperationsDemo)
 
-```csharp
-// 混合多种格式,通过 level 控制优先级
-using var cfg = new CfgBuilder()
-    .AddIni(iniPath, level: 0)
-    .AddYaml(yamlPath, level: 1)
-    .AddToml(tomlPath, level: 2, isPrimaryWriter: true)
-    .Build();
-```
+演示批量读写操作:
+- `GetMany` 批量获取配置
+- `GetMany<T>` 批量获取并转换类型
+- `SetMany` 批量设置配置
 
-### 示例 3: 配置节与子键枚举
+### 示例 5: 类型转换 (TypeConversionDemo)
 
-```csharp
-// 获取配置节简化嵌套访问
-var dbSection = cfg.GetSection("Database");
-var primarySection = dbSection.GetSection("Primary");
-var host = primarySection.Get("Host");
+演示 `Get<T>` 类型转换功能:
+- 基本类型:int、long、double、decimal、bool
+- 复杂类型:DateTime、Guid、枚举
+- 可空类型与默认值处理
 
-// 枚举子键
-foreach (var key in dbSection.GetChildKeys())
-{
-    Console.WriteLine(key);  // 输出: Primary, Replica
-}
-```
+### 示例 6: 动态重载 (DynamicReloadDemo)
 
-### 示例 4: 批量操作
+演示配置动态重载功能:
+- `reloadOnChange` 参数启用文件监听
+- `DynamicReloadOptions` 配置防抖、策略等
+- `IChangeToken` 监听配置变更
+- `ConfigChanges` (Rx) 订阅配置变更事件
 
-```csharp
-// 批量获取
-var keys = new[] { "Settings:Theme", "Settings:Language" };
-var values = cfg.GetMany(keys);
+### 示例 7: 依赖注入 (DependencyInjectionDemo)
 
-// 批量获取并转换类型
-var intValues = cfg.GetMany<int>(new[] { "Settings:FontSize" });
+演示与 Microsoft.Extensions.DependencyInjection 集成:
+- `AddApqCfg` 注册配置服务
+- `ConfigureApqCfg<T>` 绑定强类型配置
+- 通过 DI 获取 `ICfgRoot`、`IConfigurationRoot`
+- 通过 `IOptions<T>` 获取强类型配置
 
-// 批量设置
-cfg.SetMany(new Dictionary<string, string?>
-{
-    ["Settings:Theme"] = "light",
-    ["Settings:FontSize"] = "16"
-});
-```
+### 示例 8: 编码映射 (EncodingMappingDemo)
 
-### 示例 5: 类型转换
+演示编码检测和映射功能:
+- `WithEncodingConfidenceThreshold` 设置检测置信度
+- `WithEncodingDetectionLogging` 启用检测日志
+- `AddReadEncodingMapping` 指定读取编码
+- `AddWriteEncodingMappingWildcard` 通配符映射
 
-支持的类型:
-- 基本类型:`int`, `long`, `double`, `decimal`, `bool`
-- 日期时间:`DateTime`, `DateTimeOffset`
-- 其他:`Guid`, `Enum`, 可空类型
+### 示例 9: Redis 配置源 (RedisDemo)
 
-```csharp
-var intVal = cfg.Get<int>("Types:IntValue");
-var dateVal = cfg.Get<DateTime>("Types:DateValue");
-var enumVal = cfg.Get<LogLevel>("Types:EnumValue");
-var nullableVal = cfg.Get<int?>("Types:NotExist");  // 返回 null
-```
+演示 Redis 作为配置源:
+- 连接 Redis 服务器
+- 从 Redis Hash 读取配置
+- 配置键前缀和数据库选择
+- 支持配置变更监听
 
-### 示例 6: 动态配置重载
+### 示例 10: 数据库配置源 (DatabaseDemo)
 
-```csharp
-// 启用文件变更监听
-var cfg = new CfgBuilder()
-    .AddJson(configPath, reloadOnChange: true)
-    .Build();
+演示数据库作为配置源:
+- 支持 SqlSugar 多数据库(MySQL、PostgreSQL、SQLite 等)
+- 从数据库表读取配置
+- 自定义表名、键列、值列
+- 支持配置变更监听
 
-// 配置重载选项
-var msConfig = cfg.ToMicrosoftConfiguration(new DynamicReloadOptions
-{
-    DebounceMs = 100,           // 防抖时间
-    EnableDynamicReload = true,  // 启用动态重载
-    Strategy = ReloadStrategy.Eager,  // 立即重载
-    RollbackOnError = true,      // 错误时回滚
-    HistorySize = 5              // 保留历史记录数
-});
-
-// 方式1: 使用 IChangeToken
-ChangeToken.OnChange(
-    () => msConfig.GetReloadToken(),
-    () => Console.WriteLine("配置已更新"));
-
-// 方式2: 使用 Rx 订阅
-cfg.ConfigChanges.Subscribe(e =>
-{
-    foreach (var (key, change) in e.Changes)
-    {
-        Console.WriteLine($"[{change.Type}] {key}: {change.OldValue} -> {change.NewValue}");
-    }
-});
-```
+### 示例 11: Consul 配置源 (ConsulDemo)
 
-### 示例 7: 依赖注入集成
+演示 Consul KV 作为配置源:
+- 连接 Consul 服务器
+- 从 Consul KV 存储读取配置
+- 配置键前缀过滤
+- 支持 ACL Token 认证
+- 支持配置变更监听
 
-```csharp
-var services = new ServiceCollection();
+### 示例 12: Etcd 配置源 (EtcdDemo)
 
-// 注册配置服务
-services.AddApqCfg(cfg => cfg
-    .AddJson(configPath, writeable: true, isPrimaryWriter: true));
+演示 Etcd 作为配置源:
+- 连接 Etcd 集群
+- 从 Etcd 键值存储读取配置
+- 配置键前缀过滤
+- 支持用户名密码认证
+- 支持配置变更监听
 
-// 绑定强类型配置
-services.ConfigureApqCfg<DatabaseOptions>("Database");
-services.ConfigureApqCfg<LoggingOptions>("Logging");
+### 示例 13: Nacos 配置源 (NacosDemo)
 
-// 使用
-var provider = services.BuildServiceProvider();
-var cfgRoot = provider.GetRequiredService<ICfgRoot>();
-var dbOptions = provider.GetRequiredService<IOptions<DatabaseOptions>>().Value;
-```
+演示 Nacos 作为配置源:
+- 连接 Nacos 配置中心
+- 从 Nacos 读取配置
+- 配置命名空间、分组、数据ID
+- 支持用户名密码认证
+- 支持配置变更监听
+
+### 示例 14: Apollo 配置源 (ApolloDemo)
+
+演示 Apollo 作为配置源:
+- 连接 Apollo 配置中心
+- 从 Apollo 读取配置
+- 配置应用ID、集群、命名空间
+- 支持 Secret 认证
+- 支持配置变更监听
+
+### 示例 15: Zookeeper 配置源 (ZookeeperDemo)
+
+演示 Zookeeper 作为配置源:
+- 连接 Zookeeper 集群
+- 从 Zookeeper 节点读取配置
+- 配置根路径
+- 支持认证
+- 支持配置变更监听
+
+### 示例 16: HashiCorp Vault 配置源 (VaultDemo)
 
-### 示例 8: 编码映射配置
+演示 HashiCorp Vault 作为配置源:
+- 连接 Vault 服务器
+- 从 Vault KV 存储读取密钥配置
+- 配置挂载点和路径
+- 支持 Token 认证
+- 支持配置变更监听
+
+### 示例 17: 源代码生成器 (SourceGeneratorDemo)
+
+演示 Apq.Cfg.SourceGenerator 功能:
+- 使用 `[CfgSection]` 特性标记配置类
+- 自动生成配置绑定代码
+- 编译时类型安全
+- 减少运行时反射开销
+
+## 配置模型
+
+示例中使用的强类型配置模型定义在 `Models/ConfigModels.cs`:
 
 ```csharp
-var cfg = new CfgBuilder()
-    // 设置编码检测置信度阈值
-    .WithEncodingConfidenceThreshold(0.7f)
-    // 编码检测日志回调
-    .WithEncodingDetectionLogging(result =>
-    {
-        Console.WriteLine($"编码: {result.Encoding.EncodingName}");
-        Console.WriteLine($"置信度: {result.Confidence:P0}");
-        Console.WriteLine($"方法: {result.Method}");
-    })
-    // 为特定文件指定读取编码
-    .AddReadEncodingMapping(configPath, Encoding.UTF8, priority: 100)
-    // 为通配符匹配的文件指定写入编码
-    .AddWriteEncodingMappingWildcard("*.json", new UTF8Encoding(false), priority: 50)
-    // 使用正则表达式匹配
-    .AddReadEncodingMappingRegex(@"config.*\.json$", Encoding.UTF8, priority: 80)
-    .AddJson(configPath)
-    .Build();
+public class DatabaseOptions
+{
+    public string? Host { get; set; }
+    public int Port { get; set; }
+    public string? Name { get; set; }
+}
+
+public class LoggingOptions
+{
+    public string? Level { get; set; }
+    public bool EnableConsole { get; set; }
+}
+
+public enum LogLevel
+{
+    Debug, Info, Warning, Error
+}
 ```
 
-## 项目依赖
+## 支持的框架
 
-```xml
-<ItemGroup>
-  <ProjectReference Include="..\..\Apq.Cfg\Apq.Cfg.csproj" />
-  <ProjectReference Include="..\..\Apq.Cfg.Ini\Apq.Cfg.Ini.csproj" />
-  <ProjectReference Include="..\..\Apq.Cfg.Xml\Apq.Cfg.Xml.csproj" />
-  <ProjectReference Include="..\..\Apq.Cfg.Yaml\Apq.Cfg.Yaml.csproj" />
-  <ProjectReference Include="..\..\Apq.Cfg.Toml\Apq.Cfg.Toml.csproj" />
-</ItemGroup>
+- .NET 6.0
+- .NET 7.0
+- .NET 8.0
+- .NET 9.0
 
-<ItemGroup>
-  <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.1" />
-</ItemGroup>
-```
+## 依赖
 
-## 注意事项
+### 核心库
+- Apq.Cfg(核心库)
 
-1. **层级与可写性**:当最高优先级的配置源不可写时(如环境变量),调用 `Set()` 和 `SaveAsync()` 需要显式指定 `targetLevel` 参数。
+### 文件格式扩展
+- Apq.Cfg.Ini
+- Apq.Cfg.Xml
+- Apq.Cfg.Yaml
+- Apq.Cfg.Toml
 
-2. **isPrimaryWriter**:只能有一个配置源设置为 `isPrimaryWriter: true`,它将作为默认的写入目标。
+### 分布式配置源
+- Apq.Cfg.Redis
+- Apq.Cfg.Database
+- Apq.Cfg.Consul
+- Apq.Cfg.Etcd
+- Apq.Cfg.Nacos
+- Apq.Cfg.Apollo
+- Apq.Cfg.Zookeeper
+- Apq.Cfg.Vault
 
-3. **reloadOnChange**:启用后会监听文件变更,配合 `DynamicReloadOptions` 可以实现配置热更新。
+### 代码生成
+- Apq.Cfg.SourceGenerator
+
+## 注意事项
 
-4. **编码检测**:默认使用 UTF.Unknown 库进行编码检测,可通过映射规则强制指定编码。
+1. **分布式配置源示例**(示例 9-16)需要对应的服务运行才能正常工作
+2. 示例代码中的连接地址、端口、认证信息仅为演示用途,请根据实际环境修改
+3. 源代码生成器示例需要 .NET 6.0 或更高版本