ApolloDemo.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. #pragma warning disable CS0162 // 检测到无法访问的代码
  2. using Apq.Cfg;
  3. using Apq.Cfg.Apollo;
  4. namespace Apq.Cfg.Samples.Demos;
  5. /// <summary>
  6. /// 示例 14: Apollo 配置中心
  7. /// 演示如何使用 Apollo 作为配置源
  8. /// 注意:需要运行 Apollo 服务才能执行完整示例
  9. /// 快速启动:参考 https://www.apolloconfig.com/#/zh/deployment/quick-start
  10. /// </summary>
  11. public static class ApolloDemo
  12. {
  13. // 是否启用实际连接测试(设为 true 需要 Apollo 服务运行)
  14. private const bool EnableLiveTest = false;
  15. public static async Task RunAsync(string baseDir)
  16. {
  17. Console.WriteLine("═══════════════════════════════════════════════════════════════");
  18. Console.WriteLine("示例 14: Apollo 配置中心");
  19. Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
  20. Console.WriteLine("【说明】Apollo 是携程开源的分布式配置中心。");
  21. Console.WriteLine("【文档】https://www.apolloconfig.com/\n");
  22. // 示例 14.1: 基本配置
  23. Demo_BasicConfiguration();
  24. // 示例 14.2: 多命名空间
  25. Demo_MultiNamespaceConfiguration();
  26. // 示例 14.3: 集群配置
  27. Demo_ClusterConfiguration();
  28. // 示例 14.4: 访问密钥认证
  29. Demo_SecretConfiguration();
  30. // 示例 14.5: 不同数据格式
  31. Demo_DataFormatConfiguration();
  32. // 示例 14.6: 监听配置变更
  33. Demo_WatchConfiguration();
  34. // 示例 14.7: 实际连接测试
  35. if (EnableLiveTest)
  36. {
  37. await Demo_LiveTestAsync();
  38. }
  39. else
  40. {
  41. Console.WriteLine("--- 示例 14.7: 实际连接测试 ---");
  42. Console.WriteLine(" [跳过] 设置 EnableLiveTest = true 并启动 Apollo 服务后可运行\n");
  43. }
  44. Console.WriteLine("[示例 14 完成]\n");
  45. }
  46. /// <summary>
  47. /// 示例 14.1: 基本配置
  48. /// </summary>
  49. private static void Demo_BasicConfiguration()
  50. {
  51. Console.WriteLine("--- 示例 14.1: 基本配置 ---");
  52. // 方式1: 使用 Action 配置
  53. var builder1 = new CfgBuilder()
  54. .AddApollo(options =>
  55. {
  56. options.AppId = "myapp"; // 应用 ID
  57. options.MetaServer = "http://localhost:8080"; // Meta Server 地址
  58. options.Namespaces = new[] { "application" }; // 命名空间
  59. }, level: 0);
  60. Console.WriteLine(" 方式1: AddApollo(options => { ... })");
  61. Console.WriteLine(" options.AppId = \"myapp\"");
  62. Console.WriteLine(" options.MetaServer = \"http://localhost:8080\"");
  63. Console.WriteLine(" options.Namespaces = new[] { \"application\" }");
  64. // 方式2: 使用简化方法
  65. var builder2 = new CfgBuilder()
  66. .AddApollo("myapp", metaServer: "http://localhost:8080", level: 0);
  67. Console.WriteLine(" 方式2: AddApollo(\"myapp\", metaServer: \"http://localhost:8080\")");
  68. Console.WriteLine();
  69. }
  70. /// <summary>
  71. /// 示例 14.2: 多命名空间配置
  72. /// </summary>
  73. private static void Demo_MultiNamespaceConfiguration()
  74. {
  75. Console.WriteLine("--- 示例 14.2: 多命名空间 ---");
  76. // Apollo 支持多命名空间,可以将配置分类管理
  77. var builder = new CfgBuilder()
  78. .AddApollo(options =>
  79. {
  80. options.AppId = "myapp";
  81. options.MetaServer = "http://localhost:8080";
  82. options.Namespaces = new[]
  83. {
  84. "application", // 默认命名空间
  85. "database", // 数据库配置
  86. "redis", // Redis 配置
  87. "common.json" // 公共配置(JSON 格式)
  88. };
  89. }, level: 0);
  90. Console.WriteLine(" options.Namespaces = new[]");
  91. Console.WriteLine(" {");
  92. Console.WriteLine(" \"application\", // 默认命名空间");
  93. Console.WriteLine(" \"database\", // 数据库配置");
  94. Console.WriteLine(" \"redis\", // Redis 配置");
  95. Console.WriteLine(" \"common.json\" // 公共配置(JSON 格式)");
  96. Console.WriteLine(" }");
  97. Console.WriteLine();
  98. }
  99. /// <summary>
  100. /// 示例 14.3: 集群配置
  101. /// </summary>
  102. private static void Demo_ClusterConfiguration()
  103. {
  104. Console.WriteLine("--- 示例 14.3: 集群配置 ---");
  105. // Apollo 支持集群,可以为不同环境配置不同的集群
  106. var builder = new CfgBuilder()
  107. .AddApollo(options =>
  108. {
  109. options.AppId = "myapp";
  110. options.MetaServer = "http://apollo.prod.example.com:8080";
  111. options.Cluster = "SHAJQ"; // 上海机房集群
  112. options.Namespaces = new[] { "application" };
  113. }, level: 0);
  114. Console.WriteLine(" options.Cluster = \"SHAJQ\" // 上海机房集群");
  115. Console.WriteLine(" // 常见集群命名: default, SHAJQ, SHAOY, NTGXH 等");
  116. Console.WriteLine();
  117. }
  118. /// <summary>
  119. /// 示例 14.4: 访问密钥认证
  120. /// </summary>
  121. private static void Demo_SecretConfiguration()
  122. {
  123. Console.WriteLine("--- 示例 14.4: 访问密钥认证 ---");
  124. var builder = new CfgBuilder()
  125. .AddApollo(options =>
  126. {
  127. options.AppId = "myapp";
  128. options.MetaServer = "http://localhost:8080";
  129. options.Namespaces = new[] { "application" };
  130. options.Secret = "your-app-secret"; // 访问密钥
  131. options.ConnectTimeout = TimeSpan.FromSeconds(10);
  132. }, level: 0);
  133. Console.WriteLine(" options.Secret = \"your-app-secret\"");
  134. Console.WriteLine(" options.ConnectTimeout = TimeSpan.FromSeconds(10)");
  135. Console.WriteLine();
  136. }
  137. /// <summary>
  138. /// 示例 14.5: 不同数据格式
  139. /// </summary>
  140. private static void Demo_DataFormatConfiguration()
  141. {
  142. Console.WriteLine("--- 示例 14.5: 不同数据格式 ---");
  143. // Properties 格式(默认)
  144. var builder1 = new CfgBuilder()
  145. .AddApollo(options =>
  146. {
  147. options.AppId = "myapp";
  148. options.MetaServer = "http://localhost:8080";
  149. options.Namespaces = new[] { "application" };
  150. options.DataFormat = ApolloDataFormat.Properties;
  151. }, level: 0);
  152. Console.WriteLine(" Properties: options.DataFormat = ApolloDataFormat.Properties");
  153. // JSON 格式
  154. var builder2 = new CfgBuilder()
  155. .AddApollo(options =>
  156. {
  157. options.AppId = "myapp";
  158. options.MetaServer = "http://localhost:8080";
  159. options.Namespaces = new[] { "application.json" };
  160. options.DataFormat = ApolloDataFormat.Json;
  161. }, level: 0);
  162. Console.WriteLine(" JSON: options.DataFormat = ApolloDataFormat.Json");
  163. // YAML 格式
  164. var builder3 = new CfgBuilder()
  165. .AddApollo(options =>
  166. {
  167. options.AppId = "myapp";
  168. options.MetaServer = "http://localhost:8080";
  169. options.Namespaces = new[] { "application.yaml" };
  170. options.DataFormat = ApolloDataFormat.Yaml;
  171. }, level: 0);
  172. Console.WriteLine(" YAML: options.DataFormat = ApolloDataFormat.Yaml");
  173. Console.WriteLine();
  174. }
  175. /// <summary>
  176. /// 示例 14.6: 监听配置变更
  177. /// </summary>
  178. private static void Demo_WatchConfiguration()
  179. {
  180. Console.WriteLine("--- 示例 14.6: 监听配置变更 ---");
  181. var builder = new CfgBuilder()
  182. .AddApollo(options =>
  183. {
  184. options.AppId = "myapp";
  185. options.MetaServer = "http://localhost:8080";
  186. options.Namespaces = new[] { "application" };
  187. options.EnableHotReload = true; // 启用热重载(默认 true)
  188. options.LongPollingTimeout = TimeSpan.FromSeconds(90); // 长轮询超时
  189. }, level: 0);
  190. Console.WriteLine(" options.EnableHotReload = true");
  191. Console.WriteLine(" options.LongPollingTimeout = TimeSpan.FromSeconds(90)");
  192. Console.WriteLine();
  193. Console.WriteLine(" // 订阅配置变更");
  194. Console.WriteLine(" cfg.ConfigChanges.Subscribe(change =>");
  195. Console.WriteLine(" {");
  196. Console.WriteLine(" Console.WriteLine($\"配置变更: {change.Key} = {change.NewValue}\");");
  197. Console.WriteLine(" });");
  198. Console.WriteLine();
  199. }
  200. /// <summary>
  201. /// 示例 14.7: 实际连接测试
  202. /// </summary>
  203. private static async Task Demo_LiveTestAsync()
  204. {
  205. Console.WriteLine("--- 示例 14.7: 实际连接测试 ---");
  206. try
  207. {
  208. // 创建配置
  209. var cfg = new CfgBuilder()
  210. .AddApollo(options =>
  211. {
  212. options.AppId = "apq-cfg-demo";
  213. options.MetaServer = "http://localhost:8080";
  214. options.Namespaces = new[] { "application" };
  215. options.ConnectTimeout = TimeSpan.FromSeconds(3);
  216. }, level: 0)
  217. .Build();
  218. Console.WriteLine(" ✓ 连接 Apollo 成功");
  219. // 读取配置
  220. Console.WriteLine($" App:Name = {cfg.Get("App:Name") ?? "(未配置)"}");
  221. Console.WriteLine($" App:Version = {cfg.Get("App:Version") ?? "(未配置)"}");
  222. // 枚举所有键
  223. var keys = cfg.GetChildKeys();
  224. Console.WriteLine($" 配置键数量: {keys.Count()}");
  225. cfg.Dispose();
  226. }
  227. catch (Exception ex)
  228. {
  229. Console.WriteLine($" ✗ 连接失败: {ex.Message}");
  230. Console.WriteLine(" 提示: 请确保 Apollo 服务正在运行");
  231. }
  232. Console.WriteLine();
  233. await Task.CompletedTask;
  234. }
  235. }