EtcdDemo.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. #pragma warning disable CS0162 // 检测到无法访问的代码
  2. using Apq.Cfg;
  3. using Apq.Cfg.Etcd;
  4. namespace Apq.Cfg.Samples.Demos;
  5. /// <summary>
  6. /// 示例 12: Etcd 配置中心
  7. /// 演示如何使用 Etcd 作为配置源
  8. /// 注意:需要运行 Etcd 服务才能执行完整示例
  9. /// 快速启动:docker run -d -p 2379:2379 -p 2380:2380 --name etcd quay.io/coreos/etcd:latest /usr/local/bin/etcd --advertise-client-urls http://0.0.0.0:2379 --listen-client-urls http://0.0.0.0:2379
  10. /// </summary>
  11. public static class EtcdDemo
  12. {
  13. // 是否启用实际连接测试(设为 true 需要 Etcd 服务运行)
  14. private const bool EnableLiveTest = false;
  15. public static async Task RunAsync(string baseDir)
  16. {
  17. Console.WriteLine("═══════════════════════════════════════════════════════════════");
  18. Console.WriteLine("示例 12: Etcd 配置中心");
  19. Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
  20. Console.WriteLine("【说明】Etcd 是一个分布式键值存储系统,常用于服务发现和配置管理。");
  21. Console.WriteLine("【启动】docker run -d -p 2379:2379 quay.io/coreos/etcd:latest\n");
  22. // 示例 12.1: 基本配置
  23. Demo_BasicConfiguration();
  24. // 示例 12.2: 集群配置
  25. Demo_ClusterConfiguration();
  26. // 示例 12.3: 认证配置
  27. Demo_AuthConfiguration();
  28. // 示例 12.4: TLS/mTLS 配置
  29. Demo_TlsConfiguration();
  30. // 示例 12.5: 监听配置变更
  31. Demo_WatchConfiguration();
  32. // 示例 12.6: 实际连接测试
  33. if (EnableLiveTest)
  34. {
  35. await Demo_LiveTestAsync();
  36. }
  37. else
  38. {
  39. Console.WriteLine("--- 示例 12.6: 实际连接测试 ---");
  40. Console.WriteLine(" [跳过] 设置 EnableLiveTest = true 并启动 Etcd 服务后可运行\n");
  41. }
  42. Console.WriteLine("[示例 12 完成]\n");
  43. }
  44. /// <summary>
  45. /// 示例 12.1: 基本配置
  46. /// </summary>
  47. private static void Demo_BasicConfiguration()
  48. {
  49. Console.WriteLine("--- 示例 12.1: 基本配置 ---");
  50. // 方式1: 使用 Action 配置
  51. var builder1 = new CfgBuilder()
  52. .AddEtcd(options =>
  53. {
  54. options.Endpoints = new[] { "localhost:2379" }; // Etcd 端点
  55. options.KeyPrefix = "/myapp/config/"; // 键前缀
  56. }, level: 0);
  57. Console.WriteLine(" 方式1: AddEtcd(options => { ... })");
  58. Console.WriteLine(" options.Endpoints = new[] { \"localhost:2379\" }");
  59. Console.WriteLine(" options.KeyPrefix = \"/myapp/config/\"");
  60. // 方式2: 使用简化方法
  61. var builder2 = new CfgBuilder()
  62. .AddEtcd("localhost:2379", keyPrefix: "/myapp/config/", level: 0);
  63. Console.WriteLine(" 方式2: AddEtcd(\"localhost:2379\", keyPrefix: \"/myapp/config/\")");
  64. Console.WriteLine();
  65. }
  66. /// <summary>
  67. /// 示例 12.2: 集群配置(多端点)
  68. /// </summary>
  69. private static void Demo_ClusterConfiguration()
  70. {
  71. Console.WriteLine("--- 示例 12.2: 集群配置 ---");
  72. // Etcd 集群通常有多个节点,配置多个端点可提高可用性
  73. var builder = new CfgBuilder()
  74. .AddEtcd(options =>
  75. {
  76. options.Endpoints = new[]
  77. {
  78. "etcd1.example.com:2379",
  79. "etcd2.example.com:2379",
  80. "etcd3.example.com:2379"
  81. };
  82. options.KeyPrefix = "/myapp/config/";
  83. options.ConnectTimeout = TimeSpan.FromSeconds(10);
  84. options.ReconnectInterval = TimeSpan.FromSeconds(5);
  85. }, level: 0);
  86. Console.WriteLine(" options.Endpoints = new[] { \"etcd1:2379\", \"etcd2:2379\", \"etcd3:2379\" }");
  87. Console.WriteLine(" options.ConnectTimeout = TimeSpan.FromSeconds(10)");
  88. Console.WriteLine(" options.ReconnectInterval = TimeSpan.FromSeconds(5)");
  89. Console.WriteLine();
  90. }
  91. /// <summary>
  92. /// 示例 12.3: 用户名密码认证
  93. /// </summary>
  94. private static void Demo_AuthConfiguration()
  95. {
  96. Console.WriteLine("--- 示例 12.3: 用户名密码认证 ---");
  97. var builder = new CfgBuilder()
  98. .AddEtcd(options =>
  99. {
  100. options.Endpoints = new[] { "localhost:2379" };
  101. options.KeyPrefix = "/myapp/config/";
  102. options.Username = "root"; // 用户名
  103. options.Password = "your-password"; // 密码
  104. }, level: 0);
  105. Console.WriteLine(" options.Username = \"root\"");
  106. Console.WriteLine(" options.Password = \"your-password\"");
  107. Console.WriteLine();
  108. }
  109. /// <summary>
  110. /// 示例 12.4: TLS/mTLS 安全连接
  111. /// </summary>
  112. private static void Demo_TlsConfiguration()
  113. {
  114. Console.WriteLine("--- 示例 12.4: TLS/mTLS 安全连接 ---");
  115. // TLS 连接(仅验证服务器证书)
  116. var builder1 = new CfgBuilder()
  117. .AddEtcd(options =>
  118. {
  119. options.Endpoints = new[] { "etcd.example.com:2379" };
  120. options.KeyPrefix = "/myapp/config/";
  121. options.CaCertPath = "/path/to/ca.crt"; // CA 证书
  122. }, level: 0);
  123. Console.WriteLine(" TLS 连接:");
  124. Console.WriteLine(" options.CaCertPath = \"/path/to/ca.crt\"");
  125. // mTLS 连接(双向认证)
  126. var builder2 = new CfgBuilder()
  127. .AddEtcd(options =>
  128. {
  129. options.Endpoints = new[] { "etcd.example.com:2379" };
  130. options.KeyPrefix = "/myapp/config/";
  131. options.CaCertPath = "/path/to/ca.crt"; // CA 证书
  132. options.ClientCertPath = "/path/to/client.crt"; // 客户端证书
  133. options.ClientKeyPath = "/path/to/client.key"; // 客户端私钥
  134. }, level: 0);
  135. Console.WriteLine(" mTLS 连接:");
  136. Console.WriteLine(" options.CaCertPath = \"/path/to/ca.crt\"");
  137. Console.WriteLine(" options.ClientCertPath = \"/path/to/client.crt\"");
  138. Console.WriteLine(" options.ClientKeyPath = \"/path/to/client.key\"");
  139. Console.WriteLine();
  140. }
  141. /// <summary>
  142. /// 示例 12.5: 监听配置变更
  143. /// </summary>
  144. private static void Demo_WatchConfiguration()
  145. {
  146. Console.WriteLine("--- 示例 12.5: 监听配置变更 ---");
  147. var builder = new CfgBuilder()
  148. .AddEtcd(options =>
  149. {
  150. options.Endpoints = new[] { "localhost:2379" };
  151. options.KeyPrefix = "/myapp/config/";
  152. options.EnableHotReload = true; // 启用热重载(默认 true)
  153. }, level: 0);
  154. Console.WriteLine(" options.EnableHotReload = true");
  155. Console.WriteLine();
  156. Console.WriteLine(" // 订阅配置变更(使用 Etcd Watch API)");
  157. Console.WriteLine(" cfg.ConfigChanges.Subscribe(change =>");
  158. Console.WriteLine(" {");
  159. Console.WriteLine(" Console.WriteLine($\"配置变更: {change.Key}\");");
  160. Console.WriteLine(" Console.WriteLine($\" 旧值: {change.OldValue}\");");
  161. Console.WriteLine(" Console.WriteLine($\" 新值: {change.NewValue}\");");
  162. Console.WriteLine(" });");
  163. Console.WriteLine();
  164. }
  165. /// <summary>
  166. /// 示例 12.6: 实际连接测试
  167. /// </summary>
  168. private static async Task Demo_LiveTestAsync()
  169. {
  170. Console.WriteLine("--- 示例 12.6: 实际连接测试 ---");
  171. try
  172. {
  173. // 创建配置
  174. var cfg = new CfgBuilder()
  175. .AddEtcd(options =>
  176. {
  177. options.Endpoints = new[] { "localhost:2379" };
  178. options.KeyPrefix = "/apq-cfg-demo/";
  179. options.ConnectTimeout = TimeSpan.FromSeconds(3);
  180. }, level: 0, isPrimaryWriter: true)
  181. .Build();
  182. Console.WriteLine(" ✓ 连接 Etcd 成功");
  183. // 写入测试配置
  184. cfg.Set("App:Name", "EtcdDemo");
  185. cfg.Set("App:Version", "1.0.0");
  186. cfg.Set("Database:Host", "localhost");
  187. cfg.Set("Database:Port", "5432");
  188. await cfg.SaveAsync();
  189. Console.WriteLine(" ✓ 写入配置成功");
  190. // 读取配置
  191. Console.WriteLine($" App:Name = {cfg.Get("App:Name")}");
  192. Console.WriteLine($" App:Version = {cfg.Get("App:Version")}");
  193. Console.WriteLine($" Database:Host = {cfg.Get("Database:Host")}");
  194. Console.WriteLine($" Database:Port = {cfg.Get<int>("Database:Port")}");
  195. // 枚举所有键
  196. var keys = cfg.GetChildKeys();
  197. Console.WriteLine($" 配置键数量: {keys.Count()}");
  198. // 清理测试数据
  199. cfg.Remove("App:Name");
  200. cfg.Remove("App:Version");
  201. cfg.Remove("Database:Host");
  202. cfg.Remove("Database:Port");
  203. await cfg.SaveAsync();
  204. Console.WriteLine(" ✓ 清理测试数据成功");
  205. cfg.Dispose();
  206. }
  207. catch (Exception ex)
  208. {
  209. Console.WriteLine($" ✗ 连接失败: {ex.Message}");
  210. Console.WriteLine(" 提示: 请确保 Etcd 服务正在运行");
  211. }
  212. Console.WriteLine();
  213. }
  214. }