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

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

[[376036]]

本文转载自微信公众号「码农读书」,作者码农读书 。转载本文请联系码农读书公众号。

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

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

注册健康检查服务

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

  1. public class Startup 
  2.     { 
  3.  
  4.         // This method gets called by the runtime. Use this method to add services to the container. 
  5.         public void ConfigureServices(IServiceCollection services) 
  6.         { 
  7.             services.AddControllersWithViews(); 
  8.  
  9.             services.AddHealthChecks(); 
  10.         } 
  11.  
  12.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
  13.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 
  14.         { 
  15.             app.UseHealthChecks("/health"); 
  16.  
  17.             app.UseStaticFiles(); 
  18.             app.UseRouting(); 
  19.             app.UseEndpoints(endpoints => 
  20.             { 
  21.                 endpoints.MapControllerRoute( 
  22.                     name"default"
  23.                     pattern: "{controller=Home}/{action=Index}/{id?}"); 
  24.             }); 
  25.         } 
  26.     } 

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

其他服务的健康检查

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

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

  1. public void ConfigureServices(IServiceCollection services) 
  2.         { 
  3.             services.AddControllersWithViews(); 
  4.  
  5.             services.AddHealthChecks().AddSqlServer("server=.;database=PYZ_L;Trusted_Connection=SSPI"); 
  6.         } 

自定义健康检查

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

  1. public class MyCustomHealthCheck : IHealthCheck 
  2.    { 
  3.        public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, 
  4.                                                        CancellationToken cancellationToken = default(CancellationToken)) 
  5.        { 
  6.            bool canConnect = IsDBOnline(); 
  7.  
  8.            if (canConnect) 
  9.                return HealthCheckResult.Healthy(); 
  10.            return HealthCheckResult.Unhealthy(); 
  11.        } 
  12.    } 

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

  1. private bool IsDBOnline() 
  2.         { 
  3.             string connectionString = "server=.;database=PYZ_L;Trusted_Connection=SSPI"
  4.  
  5.             try 
  6.             { 
  7.                 using (SqlConnection connection = new SqlConnection(connectionString)) 
  8.                 { 
  9.                     if (connection.State != System.Data.ConnectionState.Openconnection.Open(); 
  10.                 } 
  11.  
  12.                 return true
  13.             } 
  14.             catch (System.Exception) 
  15.             { 
  16.                 return false
  17.             } 
  18.         } 

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

  1. public void ConfigureServices(IServiceCollection services) 
  2.         { 
  3.             services.AddControllersWithViews(); 
  4.             services.AddHealthChecks().AddCheck<MyCustomHealthCheck>("sqlcheck"); 
  5.         } 
  6.  
  7.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 
  8.         { 
  9.             app.UseRouting().UseEndpoints(config => 
  10.             { 
  11.                 config.MapHealthChecks("/health"); 
  12.             }); 
  13.  
  14.             app.UseStaticFiles(); 
  15.             app.UseRouting(); 
  16.  
  17.             app.UseEndpoints(endpoints => 
  18.             { 
  19.                 endpoints.MapControllerRoute( 
  20.                     name"default"
  21.                     pattern: "{controller=Home}/{action=Index}/{id?}"); 
  22.             }); 
  23.         } 

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

可视化健康检查

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

  1. Install-Package AspNetCore.HealthChecks.UI 
  2. Install-Package AspNetCore.HealthChecks.UI.Client 
  3. Install-Package AspNetCore.HealthChecks.UI.InMemory.Storage 

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

  1. public class Startup 
  2.    { 
  3.        // This method gets called by the runtime. Use this method to add services to the container. 
  4.        public void ConfigureServices(IServiceCollection services) 
  5.        { 
  6.            services.AddControllersWithViews(); 
  7.            services.AddHealthChecks(); 
  8.            services.AddHealthChecksUI().AddInMemoryStorage(); 
  9.        } 
  10.  
  11.        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
  12.        public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 
  13.        { 
  14.            
  15.            app.UseRouting().UseEndpoints(config => 
  16.            { 
  17.                config.MapHealthChecks("/health", new HealthCheckOptions 
  18.                { 
  19.                    Predicate = _ => true
  20.                    ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse 
  21.                }); 
  22.            }); 
  23.  
  24.            app.UseHealthChecksUI(); 
  25.  
  26.            app.UseStaticFiles(); 
  27.  
  28.            app.UseRouting(); 
  29.  
  30.            app.UseEndpoints(endpoints => 
  31.            { 
  32.                endpoints.MapControllerRoute( 
  33.                    name"default"
  34.                    pattern: "{controller=Home}/{action=Index}/{id?}"); 
  35.            }); 
  36.        } 
  37.    } 

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

  1.   "Logging": { 
  2.     "LogLevel": { 
  3.       "Default""Information"
  4.       "Microsoft""Warning"
  5.       "Microsoft.Hosting.Lifetime""Information" 
  6.     } 
  7.   }, 
  8.   "AllowedHosts""*"
  9.   "HealthChecks-UI": { 
  10.     "HealthChecks": [ 
  11.       { 
  12.         "Name""Local"
  13.         "Uri""http://localhost:65348/health" 
  14.       } 
  15.     ], 
  16.     "EvaluationTimeOnSeconds": 10, 
  17.     "MinimumSecondsBetweenFailureNotifications": 60 
  18.   } 

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

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

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

责任编辑:武晓燕 来源: 码农读书
相关推荐

2021-01-13 07:33:41

API数据安全

2021-03-17 09:45:31

LazyCacheWindows

2021-11-01 14:52:38

ElasticSear索引SQL

2021-02-06 21:40:13

SignalR通讯TypeScript

2021-02-02 16:19:08

Serilog日志框架

2021-03-10 09:40:43

LamarASP容器

2021-01-07 07:39:07

工具接口 Swagger

2021-02-03 13:35:25

ASPweb程序

2021-01-28 22:39:35

LoggerMessa开源框架

2021-02-28 20:56:37

NCache缓存框架

2021-03-03 22:37:16

MediatR中介者模式

2021-01-31 22:56:50

FromServiceASP

2021-01-11 05:20:05

Controller代码数据层

2021-02-07 17:29:04

监视文件接口

2021-03-18 07:33:54

PDF DinkToPdfC++

2023-03-03 08:19:35

KubernetesgRPC

2021-03-08 07:32:05

Actionweb框架

2009-08-05 11:00:46

获得RowIndexASP.NET

2023-03-02 07:20:10

GRPC服务健康检查协议

2022-08-01 08:00:00

开发工具跟踪侦听器
点赞
收藏

51CTO技术栈公众号