健康检查 罕用于判断一个应用程序是否对 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.UIInstall-Package AspNetCore.HealthChecks.UI.ClientInstall-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/art...

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