ConsulDemo.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. #pragma warning disable CS0162 // 检测到无法访问的代码
  2. using Apq.Cfg;
  3. using Apq.Cfg.Consul;
  4. namespace Apq.Cfg.Samples.Demos;
  5. /// <summary>
  6. /// 示例 11: Consul 配置中心
  7. /// 演示如何使用 Consul 作为配置源
  8. /// 注意:需要运行 Consul 服务才能执行完整示例
  9. /// 快速启动:docker run -d -p 8500:8500 consul
  10. /// </summary>
  11. public static class ConsulDemo
  12. {
  13. // 是否启用实际连接测试(设为 true 需要 Consul 服务运行)
  14. private const bool EnableLiveTest = false;
  15. public static async Task RunAsync(string baseDir)
  16. {
  17. Console.WriteLine("═══════════════════════════════════════════════════════════════");
  18. Console.WriteLine("示例 11: Consul 配置中心");
  19. Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
  20. Console.WriteLine("【说明】Consul 是 HashiCorp 开发的服务发现和配置管理工具。");
  21. Console.WriteLine("【启动】docker run -d -p 8500:8500 consul\n");
  22. // 示例 11.1: 基本配置
  23. Demo_BasicConfiguration();
  24. // 示例 11.2: 带认证的配置
  25. Demo_AuthConfiguration();
  26. // 示例 11.3: 多数据中心配置
  27. Demo_MultiDatacenterConfiguration();
  28. // 示例 11.4: 监听配置变更
  29. Demo_WatchConfiguration();
  30. // 示例 11.5: 实际连接测试
  31. if (EnableLiveTest)
  32. {
  33. await Demo_LiveTestAsync();
  34. }
  35. else
  36. {
  37. Console.WriteLine("--- 示例 11.5: 实际连接测试 ---");
  38. Console.WriteLine(" [跳过] 设置 EnableLiveTest = true 并启动 Consul 服务后可运行\n");
  39. }
  40. Console.WriteLine("[示例 11 完成]\n");
  41. }
  42. /// <summary>
  43. /// 示例 11.1: 基本配置
  44. /// </summary>
  45. private static void Demo_BasicConfiguration()
  46. {
  47. Console.WriteLine("--- 示例 11.1: 基本配置 ---");
  48. // 方式1: 使用 Action 配置
  49. var builder1 = new CfgBuilder()
  50. .AddConsul(options =>
  51. {
  52. options.Address = "http://localhost:8500"; // Consul 地址
  53. options.KeyPrefix = "myapp/config/"; // KV 前缀
  54. }, level: 0);
  55. Console.WriteLine(" 方式1: AddConsul(options => { ... })");
  56. Console.WriteLine(" options.Address = \"http://localhost:8500\"");
  57. Console.WriteLine(" options.KeyPrefix = \"myapp/config/\"");
  58. // 方式2: 使用简化方法
  59. var builder2 = new CfgBuilder()
  60. .AddConsul("http://localhost:8500", keyPrefix: "myapp/config/", level: 0);
  61. Console.WriteLine(" 方式2: AddConsul(\"http://localhost:8500\", keyPrefix: \"myapp/config/\")");
  62. Console.WriteLine();
  63. }
  64. /// <summary>
  65. /// 示例 11.2: 带 ACL Token 认证
  66. /// </summary>
  67. private static void Demo_AuthConfiguration()
  68. {
  69. Console.WriteLine("--- 示例 11.2: 带 ACL Token 认证 ---");
  70. var builder = new CfgBuilder()
  71. .AddConsul(options =>
  72. {
  73. options.Address = "http://localhost:8500";
  74. options.KeyPrefix = "myapp/config/";
  75. options.Token = "your-acl-token"; // ACL Token
  76. options.Datacenter = "dc1"; // 数据中心
  77. options.ConnectTimeout = TimeSpan.FromSeconds(10);
  78. }, level: 0);
  79. Console.WriteLine(" options.Token = \"your-acl-token\"");
  80. Console.WriteLine(" options.Datacenter = \"dc1\"");
  81. Console.WriteLine(" options.ConnectTimeout = TimeSpan.FromSeconds(10)");
  82. Console.WriteLine();
  83. }
  84. /// <summary>
  85. /// 示例 11.3: 多数据中心配置(层级覆盖)
  86. /// </summary>
  87. private static void Demo_MultiDatacenterConfiguration()
  88. {
  89. Console.WriteLine("--- 示例 11.3: 多数据中心配置 ---");
  90. // 可以从多个数据中心加载配置,实现配置的层级覆盖
  91. var builder = new CfgBuilder()
  92. // 基础配置(level: 0,最低优先级)
  93. .AddConsul(options =>
  94. {
  95. options.Address = "http://consul-dc1:8500";
  96. options.KeyPrefix = "shared/config/";
  97. options.Datacenter = "dc1";
  98. }, level: 0)
  99. // 应用特定配置(level: 1,覆盖基础配置)
  100. .AddConsul(options =>
  101. {
  102. options.Address = "http://consul-dc2:8500";
  103. options.KeyPrefix = "myapp/config/";
  104. options.Datacenter = "dc2";
  105. }, level: 1);
  106. Console.WriteLine(" level: 0 - 共享配置 (shared/config/)");
  107. Console.WriteLine(" level: 1 - 应用配置 (myapp/config/) - 覆盖共享配置");
  108. Console.WriteLine();
  109. }
  110. /// <summary>
  111. /// 示例 11.4: 监听配置变更
  112. /// </summary>
  113. private static void Demo_WatchConfiguration()
  114. {
  115. Console.WriteLine("--- 示例 11.4: 监听配置变更 ---");
  116. var builder = new CfgBuilder()
  117. .AddConsul(options =>
  118. {
  119. options.Address = "http://localhost:8500";
  120. options.KeyPrefix = "myapp/config/";
  121. options.EnableHotReload = true; // 启用热重载(默认 true)
  122. options.WaitTime = TimeSpan.FromMinutes(5); // Blocking Query 等待时间
  123. options.ReconnectInterval = TimeSpan.FromSeconds(5); // 重连间隔
  124. }, level: 0);
  125. Console.WriteLine(" options.EnableHotReload = true");
  126. Console.WriteLine(" options.WaitTime = TimeSpan.FromMinutes(5)");
  127. Console.WriteLine(" options.ReconnectInterval = TimeSpan.FromSeconds(5)");
  128. Console.WriteLine();
  129. Console.WriteLine(" // 订阅配置变更");
  130. Console.WriteLine(" cfg.ConfigChanges.Subscribe(change =>");
  131. Console.WriteLine(" {");
  132. Console.WriteLine(" Console.WriteLine($\"配置变更: {change.Key} = {change.NewValue}\");");
  133. Console.WriteLine(" });");
  134. Console.WriteLine();
  135. }
  136. /// <summary>
  137. /// 示例 11.5: 实际连接测试
  138. /// </summary>
  139. private static async Task Demo_LiveTestAsync()
  140. {
  141. Console.WriteLine("--- 示例 11.5: 实际连接测试 ---");
  142. try
  143. {
  144. // 创建配置
  145. var cfg = new CfgBuilder()
  146. .AddConsul(options =>
  147. {
  148. options.Address = "http://localhost:8500";
  149. options.KeyPrefix = "apq-cfg-demo/";
  150. options.ConnectTimeout = TimeSpan.FromSeconds(3);
  151. }, level: 0, isPrimaryWriter: true)
  152. .Build();
  153. Console.WriteLine(" ✓ 连接 Consul 成功");
  154. // 写入测试配置
  155. cfg.Set("App:Name", "ConsulDemo");
  156. cfg.Set("App:Version", "1.0.0");
  157. cfg.Set("Database:Host", "localhost");
  158. cfg.Set("Database:Port", "5432");
  159. await cfg.SaveAsync();
  160. Console.WriteLine(" ✓ 写入配置成功");
  161. // 读取配置
  162. Console.WriteLine($" App:Name = {cfg.Get("App:Name")}");
  163. Console.WriteLine($" App:Version = {cfg.Get("App:Version")}");
  164. Console.WriteLine($" Database:Host = {cfg.Get("Database:Host")}");
  165. Console.WriteLine($" Database:Port = {cfg.Get<int>("Database:Port")}");
  166. // 枚举所有键
  167. var keys = cfg.GetChildKeys();
  168. Console.WriteLine($" 配置键数量: {keys.Count()}");
  169. // 清理测试数据
  170. cfg.Remove("App:Name");
  171. cfg.Remove("App:Version");
  172. cfg.Remove("Database:Host");
  173. cfg.Remove("Database:Port");
  174. await cfg.SaveAsync();
  175. Console.WriteLine(" ✓ 清理测试数据成功");
  176. cfg.Dispose();
  177. }
  178. catch (Exception ex)
  179. {
  180. Console.WriteLine($" ✗ 连接失败: {ex.Message}");
  181. Console.WriteLine(" 提示: 请确保 Consul 服务正在运行");
  182. }
  183. Console.WriteLine();
  184. }
  185. }