ZookeeperDemo.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. #pragma warning disable CS0162 // 检测到无法访问的代码
  2. using Apq.Cfg;
  3. using Apq.Cfg.Zookeeper;
  4. namespace Apq.Cfg.Samples.Demos;
  5. /// <summary>
  6. /// 示例 15: Zookeeper 配置中心
  7. /// 演示如何使用 Zookeeper 作为配置源
  8. /// 注意:需要运行 Zookeeper 服务才能执行完整示例
  9. /// 快速启动:docker run -d -p 2181:2181 zookeeper:latest
  10. /// </summary>
  11. public static class ZookeeperDemo
  12. {
  13. // 是否启用实际连接测试(设为 true 需要 Zookeeper 服务运行)
  14. private const bool EnableLiveTest = false;
  15. public static async Task RunAsync(string baseDir)
  16. {
  17. Console.WriteLine("═══════════════════════════════════════════════════════════════");
  18. Console.WriteLine("示例 15: Zookeeper 配置中心");
  19. Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
  20. Console.WriteLine("【说明】Zookeeper 是 Apache 开源的分布式协调服务。");
  21. Console.WriteLine("【启动】docker run -d -p 2181:2181 zookeeper:latest\n");
  22. // 示例 15.1: 基本配置
  23. Demo_BasicConfiguration();
  24. // 示例 15.2: 集群配置
  25. Demo_ClusterConfiguration();
  26. // 示例 15.3: 认证配置
  27. Demo_AuthConfiguration();
  28. // 示例 15.4: 不同数据格式
  29. Demo_DataFormatConfiguration();
  30. // 示例 15.5: 监听配置变更
  31. Demo_WatchConfiguration();
  32. // 示例 15.6: 实际连接测试
  33. if (EnableLiveTest)
  34. {
  35. await Demo_LiveTestAsync();
  36. }
  37. else
  38. {
  39. Console.WriteLine("--- 示例 15.6: 实际连接测试 ---");
  40. Console.WriteLine(" [跳过] 设置 EnableLiveTest = true 并启动 Zookeeper 服务后可运行\n");
  41. }
  42. Console.WriteLine("[示例 15 完成]\n");
  43. }
  44. /// <summary>
  45. /// 示例 15.1: 基本配置
  46. /// </summary>
  47. private static void Demo_BasicConfiguration()
  48. {
  49. Console.WriteLine("--- 示例 15.1: 基本配置 ---");
  50. // 方式1: 使用 Action 配置
  51. var builder1 = new CfgBuilder()
  52. .AddZookeeper(options =>
  53. {
  54. options.ConnectionString = "localhost:2181"; // Zookeeper 连接字符串
  55. options.RootPath = "/myapp/config"; // 根路径
  56. }, level: 0);
  57. Console.WriteLine(" 方式1: AddZookeeper(options => { ... })");
  58. Console.WriteLine(" options.ConnectionString = \"localhost:2181\"");
  59. Console.WriteLine(" options.RootPath = \"/myapp/config\"");
  60. // 方式2: 使用简化方法
  61. var builder2 = new CfgBuilder()
  62. .AddZookeeper("localhost:2181", rootPath: "/myapp/config", level: 0);
  63. Console.WriteLine(" 方式2: AddZookeeper(\"localhost:2181\", rootPath: \"/myapp/config\")");
  64. Console.WriteLine();
  65. }
  66. /// <summary>
  67. /// 示例 15.2: 集群配置(多节点)
  68. /// </summary>
  69. private static void Demo_ClusterConfiguration()
  70. {
  71. Console.WriteLine("--- 示例 15.2: 集群配置 ---");
  72. // Zookeeper 集群通常有多个节点
  73. var builder = new CfgBuilder()
  74. .AddZookeeper(options =>
  75. {
  76. // 多节点连接字符串,用逗号分隔
  77. options.ConnectionString = "zk1.example.com:2181,zk2.example.com:2181,zk3.example.com:2181";
  78. options.RootPath = "/myapp/config";
  79. options.SessionTimeout = TimeSpan.FromSeconds(30);
  80. options.ConnectTimeout = TimeSpan.FromSeconds(10);
  81. options.ReconnectInterval = TimeSpan.FromSeconds(5);
  82. }, level: 0);
  83. Console.WriteLine(" options.ConnectionString = \"zk1:2181,zk2:2181,zk3:2181\"");
  84. Console.WriteLine(" options.SessionTimeout = TimeSpan.FromSeconds(30)");
  85. Console.WriteLine(" options.ConnectTimeout = TimeSpan.FromSeconds(10)");
  86. Console.WriteLine(" options.ReconnectInterval = TimeSpan.FromSeconds(5)");
  87. Console.WriteLine();
  88. }
  89. /// <summary>
  90. /// 示例 15.3: 认证配置
  91. /// </summary>
  92. private static void Demo_AuthConfiguration()
  93. {
  94. Console.WriteLine("--- 示例 15.3: 认证配置 ---");
  95. var builder = new CfgBuilder()
  96. .AddZookeeper(options =>
  97. {
  98. options.ConnectionString = "localhost:2181";
  99. options.RootPath = "/myapp/config";
  100. options.AuthScheme = "digest"; // 认证方案
  101. options.AuthInfo = "user:password"; // 认证信息
  102. }, level: 0);
  103. Console.WriteLine(" options.AuthScheme = \"digest\"");
  104. Console.WriteLine(" options.AuthInfo = \"user:password\"");
  105. Console.WriteLine();
  106. }
  107. /// <summary>
  108. /// 示例 15.4: 不同数据格式
  109. /// </summary>
  110. private static void Demo_DataFormatConfiguration()
  111. {
  112. Console.WriteLine("--- 示例 15.4: 不同数据格式 ---");
  113. // KeyValue 格式(默认)- 每个 ZNode 对应一个配置项
  114. var builder1 = new CfgBuilder()
  115. .AddZookeeper(options =>
  116. {
  117. options.ConnectionString = "localhost:2181";
  118. options.RootPath = "/myapp/config";
  119. options.DataFormat = ZookeeperDataFormat.KeyValue;
  120. }, level: 0);
  121. Console.WriteLine(" KeyValue: options.DataFormat = ZookeeperDataFormat.KeyValue");
  122. Console.WriteLine(" // 节点路径即为配置键,如 /myapp/config/Database/Host");
  123. // JSON 格式 - 单个节点存储 JSON 配置
  124. var builder2 = new CfgBuilder()
  125. .AddZookeeper(options =>
  126. {
  127. options.ConnectionString = "localhost:2181";
  128. options.RootPath = "/myapp";
  129. options.DataFormat = ZookeeperDataFormat.Json;
  130. options.SingleNode = "config"; // 读取 /myapp/config 节点
  131. }, level: 0);
  132. Console.WriteLine(" JSON: options.DataFormat = ZookeeperDataFormat.Json");
  133. Console.WriteLine(" options.SingleNode = \"config\" // 读取 /myapp/config 节点");
  134. Console.WriteLine();
  135. }
  136. /// <summary>
  137. /// 示例 15.5: 监听配置变更
  138. /// </summary>
  139. private static void Demo_WatchConfiguration()
  140. {
  141. Console.WriteLine("--- 示例 15.5: 监听配置变更 ---");
  142. var builder = new CfgBuilder()
  143. .AddZookeeper(options =>
  144. {
  145. options.ConnectionString = "localhost:2181";
  146. options.RootPath = "/myapp/config";
  147. options.EnableHotReload = true; // 启用热重载(默认 true)
  148. }, level: 0);
  149. Console.WriteLine(" options.EnableHotReload = true");
  150. Console.WriteLine();
  151. Console.WriteLine(" // 订阅配置变更(使用 Zookeeper Watch 机制)");
  152. Console.WriteLine(" cfg.ConfigChanges.Subscribe(change =>");
  153. Console.WriteLine(" {");
  154. Console.WriteLine(" Console.WriteLine($\"配置变更: {change.Key}\");");
  155. Console.WriteLine(" Console.WriteLine($\" 旧值: {change.OldValue}\");");
  156. Console.WriteLine(" Console.WriteLine($\" 新值: {change.NewValue}\");");
  157. Console.WriteLine(" });");
  158. Console.WriteLine();
  159. }
  160. /// <summary>
  161. /// 示例 15.6: 实际连接测试
  162. /// </summary>
  163. private static async Task Demo_LiveTestAsync()
  164. {
  165. Console.WriteLine("--- 示例 15.6: 实际连接测试 ---");
  166. try
  167. {
  168. // 创建配置
  169. var cfg = new CfgBuilder()
  170. .AddZookeeper(options =>
  171. {
  172. options.ConnectionString = "localhost:2181";
  173. options.RootPath = "/apq-cfg-demo";
  174. options.ConnectTimeout = TimeSpan.FromSeconds(3);
  175. }, level: 0, isPrimaryWriter: true)
  176. .Build();
  177. Console.WriteLine(" ✓ 连接 Zookeeper 成功");
  178. // 写入测试配置
  179. cfg.Set("App:Name", "ZookeeperDemo");
  180. cfg.Set("App:Version", "1.0.0");
  181. cfg.Set("Database:Host", "localhost");
  182. cfg.Set("Database:Port", "5432");
  183. await cfg.SaveAsync();
  184. Console.WriteLine(" ✓ 写入配置成功");
  185. // 读取配置
  186. Console.WriteLine($" App:Name = {cfg.Get("App:Name")}");
  187. Console.WriteLine($" App:Version = {cfg.Get("App:Version")}");
  188. Console.WriteLine($" Database:Host = {cfg.Get("Database:Host")}");
  189. Console.WriteLine($" Database:Port = {cfg.Get<int>("Database:Port")}");
  190. // 枚举所有键
  191. var keys = cfg.GetChildKeys();
  192. Console.WriteLine($" 配置键数量: {keys.Count()}");
  193. // 清理测试数据
  194. cfg.Remove("App:Name");
  195. cfg.Remove("App:Version");
  196. cfg.Remove("Database:Host");
  197. cfg.Remove("Database:Port");
  198. await cfg.SaveAsync();
  199. Console.WriteLine(" ✓ 清理测试数据成功");
  200. cfg.Dispose();
  201. }
  202. catch (Exception ex)
  203. {
  204. Console.WriteLine($" ✗ 连接失败: {ex.Message}");
  205. Console.WriteLine(" 提示: 请确保 Zookeeper 服务正在运行");
  206. }
  207. Console.WriteLine();
  208. }
  209. }