当前位置: 移动技术网 > IT编程>开发语言>.net > .Net Core实现健康检查的示例代码

.Net Core实现健康检查的示例代码

2020年03月09日  | 移动技术网IT编程  | 我要评论

小丑与天鹅,china细小软,太原北屯施工3名男子触电身亡!

asp.net core 提供运行状况检查中间件和库,以用于报告应用基础结构组件的运行状况。

运行状况检查由应用程序作为 http 终结点公开。 可以为各种实时监视方案配置运行状况检查终结点:

  • 运行状况探测可以由容器业务流程协调程和负载均衡器用于检查应用的状态。 例如,容器业务流程协调程序可以通过停止滚动部署或重新启动容器来响应失败的运行状况检查。 负载均衡器可以通过将流量从失败的实例路由到正常实例,来应对不正常的应用。
  • 可以监视内存、磁盘和其他物理服务器资源的使用情况来了解是否处于正常状态。
  • 运行状况检查可以测试应用的依赖项(如数据库和外部服务终结点)以确认是否可用和正常工作。

这个示例展示数据库的运行状态,他在其验证数据库连接并返回相应的结果

 [route("health")]
    public actionresult health()
    {
      using (var connection = new sqlconnection("server=.;initial catalog=master;integrated security=true"))
      {
        try
        {
          connection.open();
        }
        catch (sqlexception)
        {
          return new statuscoderesult(503);
        
        }
      }

      return new emptyresult();
    }

当我们请求该地址的时候时,如果连接到数据库时出现任何连接问题,它将显示一条包含200状态代码和503状态代码的空消息​​。

现在基于这些结果状态码,我们可以监视系统采取相关的操作。

从.net core2.2开始,我们不需要为运行状态在去自定义检查控制器和接口,而是框架本身已经为我们提供了运行状况的检查服务。

安装和运行

install-package microsoft.extensions.diagnostics.healthchecks

安装后,我们需要在startup.cs文件的configureservices()和configure()方法中添加。

  public void configureservices(iservicecollection services)
    {
      services.addhealthchecks();
    }
    public void configure(iapplicationbuilder app, iwebhostenvironment env)
    {
      app
        .usehealthchecks("/health");
     
    }

我们在configure()方法中配置完端点后,我们就可以通过 /health 来请求查看我们的应用程序的健康程度的。

但是这样对于我们刚才的需求是满足不了的,那么我们如何自定义我们的健康度检查呢?

两种方式来处理

option 1

   public void configureservices(iservicecollection services)
    {
      services.addhealthchecks()
 .addcheck("sql", () =>
 {

   using (var connection = new sqlconnection("server=.;initial catalog=master;integrated security=true"))
   {
     try
     {
       connection.open();
     }
     catch (sqlexception)
     {
       return healthcheckresult.unhealthy();
     }
   }

   return healthcheckresult.healthy();

 });
    }

在这里我们使用匿名方法addcheck(),来编写我们的自定义的验证逻辑,结果是healthcheckresult对象,该对象包含3个选项

  • healthy 健康
  • unhealthy 不良
  • degraded 降级

option 2

实现ihealthcheck接口并实现checkhealthasync()方法,如下所示:

 public class databasehealthcheck : ihealthcheck
    {
      public task<healthcheckresult> checkhealthasync(healthcheckcontext context, cancellationtoken cancellationtoken =
       default)
      {
        using (var connection = new sqlconnection("server=.;initial catalog=master;integrated security=true"))
        {
          try
          {
            connection.open();
          }
          catch (sqlexception)
          {
            return task.fromresult(healthcheckresult.unhealthy());
          }
        }

        return task.fromresult(healthcheckresult.healthy());

      }
    }

创建该类之后,我们需要通过使用一些有效的唯一名称,addcheck ()方法在configureservices()方法中提及该类,如下所示。

  public void configureservices(iservicecollection services)
    {
      services.addhealthchecks() 
     .addcheck<databasehealthcheck>("sql");
    }

现在我们的代码就写完了,我们可以像上面那样添加任意数量的health task,它将按照我们在此处声明的顺序运行。

自定义状态码

在之前我们也说过200为健康,503为不健康那么healthcheck服务甚至通过以下方式使用其options对象提供自定义状态代码,为我们提供了更改此默认的状态码。

config.maphealthchecks("/health", new healthcheckoptions
           {
            resultstatuscodes = new dictionary<healthstatus, int> { { healthstatus.unhealthy, 420 }, { healthstatus.healthy, 200 }, { healthstatus.degraded, 419 } }

             
           }); 

自定义输出

我们可以自定义输出,以获取有关每个运行状况检查任务的更清晰详细的信息。如果我们有多个运行状况检查任务来分析哪个任务使整个服务健康状态变为”不正常“,这将非常有用。

我们可以通过healthcheckoptions responsewriter属性来实现。

   public void configure(iapplicationbuilder app, iwebhostenvironment env)
    {
      app
         .userouting()
         .useendpoints(config =>
         {
           config.maphealthchecks("/health", new healthcheckoptions
           {
            responsewriter=customresponsewriter
            
           }); 

         });

    }
    private static task customresponsewriter(httpcontext context, healthreport healthreport)
    {
      context.response.contenttype = "application/json";

      var result = jsonconvert.serializeobject(new
      {
        status = healthreport.status.tostring(),
        errors = healthreport.entries.select(e => new
        {
          key = e.key,
          value = e.value.status.tostring()
        })
      });
      return context.response.writeasync(result);

    }

现在以json显示我们的详细信息,完成了健康状态的检查.

健康检查界面

install-package aspnetcore.healthchecks.ui

安装完成后,需要相应地在configureservices()和configure()方法中调用相应的服务方法。

public void configureservices(iservicecollection services) 
{ 
  services.addhealthchecksui(); 
} 
 
public void configure(iapplicationbuilder app, ihostingenvironment env) 
{ 
  app.usehealthchecksui(); 
} 

配置完成后,您可以运行应用程序并指向/ healthchecks-ui地址,该端点显示如下的ui.

但是界面上没有我们刚才自定义的,那我们在进行配置

appsetting.json

{
 "applicationinsights": {
  "instrumentationkey": "your-instrumentation-key"
 },
 "logging": {
  "loglevel": {
   "default": "warning"
  }
 },
 "allowedhosts": "*",
 "healthchecksui": {
  "healthchecks": [
   {
    "name": "test health",
    "uri": "https://localhost:44342/health"
   }
  ],
  "evaluationtimeinseconds": 10,
  "minimumsecondsbetweenfailurenotifications": 60
 }
}

这样就可以看到健康状态了

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网