edison0621

写在前面

前文讨论了HealthCheck的理论部分,本文将讨论有关HealthCheck的应用内容。

  • 可以监视内存、磁盘和其他物理服务器资源的使用情况来了解是否处于正常状态。
  • 运行状况检查可以测试应用的依赖项(如数据库和外部服务终结点)以确认是否可用和正常工作。
  • 运行状况探测可以由容器业务流程协调程序和负载均衡器用于检查应用的状态。

源码研究

在应用中引入HealthCheck,一般需要配置Startup文件,如下所示:

   1:  public void ConfigureServices(IServiceCollection services)
   2:  {
   3:      services.AddHealthChecks();
   4:  }
   5:   
   6:  public void Configure(IApplicationBuilder app)
   7:  {
   8:       app.UseRouting();
   9:   
  10:       app.UseEndpoints(endpoints =>
  11:        {
  12:            endpoints.MapHealthChecks("/health");
  13:        });
  14:  }

其中services.AddHealthChecks();会把我们引入到HealthCheckService的扩展方法中,代码如下:

   1:  public static class HealthCheckServiceCollectionExtensions
   2:  {
   3:      public static IHealthChecksBuilder AddHealthChecks(this IServiceCollection services)
   4:      {
   5:          services.TryAddSingleton<HealthCheckService, DefaultHealthCheckService>();
   6:          services.TryAddEnumerable(ServiceDescriptor.Singleton<IHostedService, HealthCheckPublisherHostedService>());
   7:          return new HealthChecksBuilder(services);
   8:      }
   9:  }

该扩展方法会尝试注册一个HealthCheckService的单例对象。HealthCheckService本身是一个抽象类,它内部含有一个抽象方法,主要用于执行健康检查并返回健康状态的聚合信息。抽象方法如下所示:

   1:  public abstract Task<HealthReport> CheckHealthAsync(
   2:              Func<HealthCheckRegistration, bool> predicate,
   3:              CancellationToken cancellationToken = default);

HealthCheckService有一个默认派生类,就是DefaultHealthCheckService,在其构造方法中,会去验证是否有重复的健康检查名称存在,如果有,就会抛出异常。另外名称的检查是不区分大小写的。该类所实现的抽象方法作为健康检查的核心功能,内部实现还是比较复杂的。

首先我们看一下该方法的实现源码:

   1:  public override async Task<HealthReport> CheckHealthAsync(
   2:      Func<HealthCheckRegistration, bool> predicate,
   3:      CancellationToken cancellationToken = default)
   4:  {
   5:      var registrations = _options.Value.Registrations;
   6:      if (predicate != null)
   7:      {
   8:          registrations = registrations.Where(predicate).ToArray();
   9:      }
  10:   
  11:      var totalTime = ValueStopwatch.StartNew();
  12:      Log.HealthCheckProcessingBegin(_logger);
  13:   
  14:      var tasks = new Task<HealthReportEntry>[registrations.Count];
  15:      var index = 0;
  16:      using (var scope = _scopeFactory.CreateScope())
  17:      {
  18:          foreach (var registration in registrations)
  19:          {
  20:              tasks[index++] = Task.Run(() => RunCheckAsync(scope, registration, cancellationToken), cancellationToken);
  21:          }
  22:   
  23:          await Task.WhenAll(tasks).ConfigureAwait(false);
  24:      }
  25:   
  26:      index = 0;
  27:      var entries = new Dictionary<string, HealthReportEntry>(StringComparer.OrdinalIgnoreCase);
  28:      foreach (var registration in registrations)
  29:      {
  30:          entries[registration.Name] = tasks[index++].Result;
  31:      }
  32:   
  33:      var totalElapsedTime = totalTime.GetElapsedTime();
  34:      var report = new HealthReport(entries, totalElapsedTime);
  35:      Log.HealthCheckProcessingEnd(_logger, report.Status, totalElapsedTime);
  36:      return report;
  37:  }

1、其内部有比较完善的监控机制,会在内部维护了一个Log功能,全程监控健康检查的耗时,该日志所记录的健康检查不仅仅是一个健康检查集合的耗时,而且也记录了每个Name的耗时。

2、该方法会通过await Task.WhenAll(tasks).ConfigureAwait(false);并发执行健康检查。当然,我需要注意的是,过多的健康检查任务将会导致系统性能的下降,这主要看如何取舍了

CheckHealthAsync内部还会调用一个私有方法RunCheckAsync,这是真正执行健康检查的方法。RunCheckAsync方法执行完成后,会创建HealthReportEntry对象返回到CheckHealthAsync中,并组装到HealthReport对象中,到此该抽象方法执行完毕。

来自官方的应用

分类:

技术点:

相关文章: