DynamicReloadDemo.cs 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using Apq.Cfg.Changes;
  2. using Microsoft.Extensions.Primitives;
  3. namespace Apq.Cfg.Samples.Demos;
  4. /// <summary>
  5. /// 示例 6: 动态配置重载
  6. /// </summary>
  7. public static class DynamicReloadDemo
  8. {
  9. public static async Task RunAsync(string baseDir)
  10. {
  11. Console.WriteLine("═══════════════════════════════════════════════════════════════");
  12. Console.WriteLine("示例 6: 动态配置重载");
  13. Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
  14. var configPath = Path.Combine(baseDir, "reload-demo.json");
  15. File.WriteAllText(configPath, """
  16. {
  17. "App": {
  18. "RefreshInterval": "30"
  19. }
  20. }
  21. """);
  22. // 启用 reloadOnChange
  23. var cfg = new CfgBuilder()
  24. .AddJson(configPath, level: 0, writeable: true, isPrimaryWriter: true, reloadOnChange: true)
  25. .Build();
  26. Console.WriteLine("6.1 配置动态重载选项:");
  27. var msConfig = cfg.ToMicrosoftConfiguration(new DynamicReloadOptions
  28. {
  29. DebounceMs = 100, // 防抖时间
  30. EnableDynamicReload = true, // 启用动态重载
  31. Strategy = ReloadStrategy.Eager, // 立即重载
  32. RollbackOnError = true, // 错误时回滚
  33. HistorySize = 5 // 保留 5 条历史
  34. });
  35. Console.WriteLine(" 已配置: DebounceMs=100, Strategy=Eager, HistorySize=5");
  36. // 使用 IChangeToken 监听变更
  37. Console.WriteLine("\n6.2 使用 IChangeToken 监听变更:");
  38. var changeCount = 0;
  39. ChangeToken.OnChange(
  40. () => msConfig.GetReloadToken(),
  41. () =>
  42. {
  43. changeCount++;
  44. Console.WriteLine($" [IChangeToken] 配置已更新 (第 {changeCount} 次)");
  45. });
  46. Console.WriteLine(" 已注册 IChangeToken 回调");
  47. // 使用 Rx 订阅配置变更
  48. Console.WriteLine("\n6.3 使用 Rx 订阅配置变更:");
  49. using var subscription = cfg.ConfigChanges.Subscribe(e =>
  50. {
  51. Console.WriteLine($" [Rx] 批次 {e.BatchId} - {e.Changes.Count} 个变更:");
  52. foreach (var (key, change) in e.Changes)
  53. {
  54. Console.WriteLine($" [{change.Type}] {key}: {change.OldValue} -> {change.NewValue}");
  55. }
  56. });
  57. Console.WriteLine(" 已订阅 ConfigChanges");
  58. // 模拟配置变更
  59. Console.WriteLine("\n6.4 模拟配置变更:");
  60. Console.WriteLine(" 修改 App:RefreshInterval 为 60...");
  61. cfg.Set("App:RefreshInterval", "60");
  62. await cfg.SaveAsync();
  63. // 等待变更通知
  64. await Task.Delay(200);
  65. Console.WriteLine($"\n 当前值: App:RefreshInterval = {cfg.Get("App:RefreshInterval")}");
  66. cfg.Dispose();
  67. File.Delete(configPath);
  68. Console.WriteLine("\n[示例 6 完成]\n");
  69. }
  70. }