如何在 ASP.Net Core 中实现 健康检查

健康检查 常用于判断一个应用程序能否对 request 请求进行响应,ASP.Net Core 2.2 中引入了 健康检查 中间件用于报告应用程序的健康状态。

ASP.Net Core 中的 健康检查 落地做法是暴露一个可配置的 Http 端口,你可以使用 健康检查 去做一个最简单的活性检测,比如说:检查网络和系统的资源可用性,数据库资源是否可用,应用程序依赖的消息中间件或者 Azure cloud service 的可用性 等等,这篇文章我们就来讨论如何使用这个 健康检查中间件。

注册健康检查服务

要注册 健康检查 服务,需要在 Startup.ConfigureServices 下调用 AddHealthChecks 方法,然后使用 UseHealthChecks 将其注入到 Request Pipeline 管道中,如下代码所示:


    public class Startup
    {

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            services.AddHealthChecks();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseHealthChecks("/health");

            app.UseStaticFiles();
            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }

上图的 /health 就是一个可供检查此 web 是否存活的暴露端口。

其他服务的健康检查

除了web的活性检查,还可以检查诸如:SQL Server, MySQL, MongoDB, Redis, RabbitMQ, Elasticsearch, Hangfire, Kafka, Oracle, Azure Storage 等一系列服务应用的活性,每一个服务需要引用相关的 nuget 包即可,如下图所示:

然后在 ConfigureServices 中添加相关服务即可,比如下面代码的 AddSqlServer


        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            services.AddHealthChecks().AddSqlServer("server=.;database=PYZ_L;Trusted_Connection=SSPI");
        }

自定义健康检查

除了上面的一些开源方案,还可以自定义实现 健康检查 类,比如自定义方式来检测 数据库外部服务 的可用性,那怎么实现呢? 只需要实现系统内置的 IHealthCheck 接口并实现 CheckHealthAsync() 即可,如下代码所示:


    public class MyCustomHealthCheck : IHealthCheck
    {
        public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context,
                                                        CancellationToken cancellationToken = default(CancellationToken))
        {
            bool canConnect = IsDBOnline();

            if (canConnect)
                return HealthCheckResult.Healthy();
            return HealthCheckResult.Unhealthy();
        }
    }

这里的 IsDBOnline 方法用来判断当前数据库是否是运行状态,实现代码如下:


        private bool IsDBOnline()
        {
            string connectionString = "server=.;database=PYZ_L;Trusted_Connection=SSPI";

            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    if (connection.State != System.Data.ConnectionState.Open) connection.Open();
                }

                return true;
            }
            catch (System.Exception)
            {
                return false;
            }
        }

然后在 ConfigureServices 方法中进行注入。


        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddHealthChecks().AddCheck<MyCustomHealthCheck>("sqlcheck");
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRouting().UseEndpoints(config =>
            {
                config.MapHealthChecks("/health");
            });

            app.UseStaticFiles();
            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }

接下来可以浏览下 /health 页面,可以看出该端口自动执行了你的 MyCustomHealthCheck 方法,如下图所示:

可视化健康检查

上面的检查策略虽然好,但并没有一个好的可视化方案,要想实现可视化的话,还需要单独下载 Nuget 包: AspNetCore.HealthChecks.UI , HealthChecks.UI.ClientAspNetCore.HealthChecks.UI.InMemory.Storage,命令如下:


Install-Package AspNetCore.HealthChecks.UI
Install-Package AspNetCore.HealthChecks.UI.Client
Install-Package AspNetCore.HealthChecks.UI.InMemory.Storage

一旦包安装好之后,就可以在 ConfigureServices 和 Configure 方法下做如下配置。


    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddHealthChecks();
            services.AddHealthChecksUI().AddInMemoryStorage();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            app.UseRouting().UseEndpoints(config =>
            {
                config.MapHealthChecks("/health", new HealthCheckOptions
                {
                    Predicate = _ => true,
                    ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
                });
            });

            app.UseHealthChecksUI();

            app.UseStaticFiles();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }

最后还要在 appsettings.json 中配一下 HealthChecks-UI 中的检查项,如下代码所示:


{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "HealthChecks-UI": {
    "HealthChecks": [
      {
        "Name": "Local",
        "Uri": "http://localhost:65348/health"
      }
    ],
    "EvaluationTimeOnSeconds": 10,
    "MinimumSecondsBetweenFailureNotifications": 60
  }
}

最后在浏览器中输入 /healthchecks-ui 看一下 可视化UI 长成啥样。

使用 ASP.Net Core 的 健康检查中间件 可以非常方便的对 系统资源,数据库 或者其他域外资源进行监控,你可以使用自定义检查逻辑来判断什么样的情况算是 Healthy,什么样的算是 UnHealthy,值得一提的是,当检测到失败时还可以使用失败通知机制,类似 github 发布钩子。

译文链接:https://www.infoworld.com/article/3379187/how-to-implement-health-checks-in-aspnet-core.html

更多高质量干货:参见我的 GitHub: csharptranslate

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ASP.NET Core实现自定义验证特性(Custom Validation Attribute)的步骤如下: 1. 创建一个继承自`ValidationAttribute`的自定义验证特性类,例如: ```csharp public class CustomValidationAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { // 验证逻辑 if (value is string str && str == "abc") { return ValidationResult.Success; } else { return new ValidationResult("必须是 abc"); } } } ``` 其,`IsValid`方法是用来进行验证的,它接收两个参数:要验证的值和验证上下文。在该方法,可以编写自定义的验证逻辑,并返回`ValidationResult`类型的结果。 2. 在需要验证的模型属性上添加自定义验证特性,例如: ```csharp public class MyModel { [CustomValidation] public string MyProperty { get; set; } } ``` 在这个例子,`MyProperty`属性上添加了`CustomValidation`特性,表示在验证该属性时,会调用`CustomValidationAttribute`类的`IsValid`方法。 3. 在控制器进行验证,例如: ```csharp [HttpPost] public IActionResult MyAction([FromBody] MyModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } // 其他逻辑 return Ok(); } ``` 在这个例子,控制器的`MyAction`方法接收一个`MyModel`类型的参数,该参数会被自动绑定到请求体。在方法,可以通过`ModelState.IsValid`属性来判断模型是否验证通过,如果验证失败,则返回`BadRequest`结果,并将`ModelState`作为响应体返回。 以上就是在ASP.NET Core实现自定义验证特性的步骤。需要注意的是,自定义验证特性只是一种验证方式,如果需要更复杂的验证逻辑,可以使用`IValidatableObject`接口或自定义验证器来实现

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值