ZookeeperBenchmarks.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. using Apq.Cfg.Zookeeper;
  2. using BenchmarkDotNet.Attributes;
  3. namespace Apq.Cfg.Benchmarks;
  4. /// <summary>
  5. /// Zookeeper 配置中心性能测试
  6. /// 注意:需要运行 Zookeeper 服务才能执行此测试
  7. /// </summary>
  8. [MemoryDiagnoser]
  9. [Config(typeof(BenchmarkConfig))]
  10. public class ZookeeperBenchmarks
  11. {
  12. private const string ConnectionString = "localhost:2181";
  13. private const string RootPath = "/benchmark/config";
  14. private ICfgRoot? _cfg;
  15. private bool _isZookeeperAvailable;
  16. [GlobalSetup]
  17. public void Setup()
  18. {
  19. try
  20. {
  21. _cfg = new CfgBuilder()
  22. .AddZookeeper(options =>
  23. {
  24. options.ConnectionString = ConnectionString;
  25. options.RootPath = RootPath;
  26. options.EnableHotReload = false;
  27. options.ConnectTimeout = TimeSpan.FromSeconds(3);
  28. }, level: 0, isPrimaryWriter: true)
  29. .Build();
  30. // 初始化测试数据
  31. for (int i = 0; i < 100; i++)
  32. {
  33. _cfg.Set($"Key{i}", $"Value{i}");
  34. }
  35. _cfg.SaveAsync().GetAwaiter().GetResult();
  36. _isZookeeperAvailable = true;
  37. }
  38. catch
  39. {
  40. _isZookeeperAvailable = false;
  41. }
  42. }
  43. [GlobalCleanup]
  44. public void Cleanup()
  45. {
  46. if (_cfg != null && _isZookeeperAvailable)
  47. {
  48. // 清理测试数据
  49. try
  50. {
  51. for (int i = 0; i < 100; i++)
  52. {
  53. _cfg.Remove($"Key{i}");
  54. }
  55. _cfg.SaveAsync().GetAwaiter().GetResult();
  56. }
  57. catch { }
  58. _cfg.Dispose();
  59. }
  60. }
  61. [Benchmark]
  62. public string? Zookeeper_Get()
  63. {
  64. if (!_isZookeeperAvailable) return null;
  65. return _cfg!.Get("Key0");
  66. }
  67. [Benchmark]
  68. public void Zookeeper_Set()
  69. {
  70. if (!_isZookeeperAvailable) return;
  71. _cfg!.Set("BenchmarkKey", "BenchmarkValue");
  72. }
  73. [Benchmark]
  74. public bool Zookeeper_Exists()
  75. {
  76. if (!_isZookeeperAvailable) return false;
  77. return _cfg!.Exists("Key0");
  78. }
  79. [Benchmark]
  80. public void Zookeeper_Get_Multiple()
  81. {
  82. if (!_isZookeeperAvailable) return;
  83. for (int i = 0; i < 10; i++)
  84. {
  85. _ = _cfg!.Get($"Key{i}");
  86. }
  87. }
  88. [Benchmark]
  89. public void Zookeeper_Set_Multiple()
  90. {
  91. if (!_isZookeeperAvailable) return;
  92. for (int i = 0; i < 10; i++)
  93. {
  94. _cfg!.Set($"BenchmarkKey{i}", $"Value{i}");
  95. }
  96. }
  97. [Benchmark]
  98. public int Zookeeper_Get_Int()
  99. {
  100. if (!_isZookeeperAvailable) return 0;
  101. _cfg!.Set("IntKey", "42");
  102. return _cfg.Get<int>("IntKey");
  103. }
  104. }