当前位置: 首页 > 科技观察

ASP.NetCore如何实现健康检查

时间:2023-03-22 12:14:38 科技观察

本文转载自微信公众号《码农读书》,作者码农读书。转载本文请联系码农阅读公众号。健康检查常用于判断一个应用程序是否可以响应request请求。ASP.NetCore2.2引入了健康检查中间件来报告应用程序的健康状态。ASP.NetCore中健康检查的实现方式是暴露一个可配置的Http端口。您可以使用健康检查来做最简单的活动检测,例如:检查网络和系统资源的可用性、数据库资源是否可用、应用程序依赖的消息中间件或Azure云服务的可用性等。在这篇文章,我们将讨论如何使用这个健康检查中间件。注册健康检查服务注册健康检查服务需要调用Startup.ConfigureServices下的AddHealthChecks方法,然后使用UseHealthChecks将其注入到RequestPipeline管道中,如下代码所示:publicclassStartup{//Thismethodgetscalledbytheruntime。Usethismethodtoaddservicestothecontainer.publicvoidConfigureServices(IServiceCollectionservices){services.AddControllersWithViews();services.AddHealthChecks();}//Thismethodgetscalledbytheruntime.UsethismethodtoconfiguretheHTTPrequestpipeline.publicvoidConfigure(IApplicationBuilderapp,IWebHostEnvironmentenv){app.UseHealthChecks("/health");app.UseappFile();app.UseappFile();()UseEndpoints(endpoints=>{endpoints.MapControllerRoute(name:"default",pattern:"{controller=Home}/{action=Index}/{id?}");});}}/health中的上图是一个暴露的端口,可以检查这个网站是否还活着。其他服务的健康检查除了web活动检查,还可以检查一系列服务应用程序的活动,如:SQLServer、MySQL、MongoDB、Redis、RabbitMQ、Elasticsearch、Hangfire、Kafka、Oracle、AzureStorage等.每个服务都需要引用相关的nuget包就可以了,如下图:然后在ConfigureServices中添加相关服务,比如下面代码中的AddSqlServer。publicvoidConfigureServices(IServiceCollectionservices){services.AddControllersWithViews();services.AddHealthChecks().AddSqlServer("server=.;database=PYZ_L;Trusted_Connection=SSPI");}自定义健康检查除了上面的一些开源解决方案,也可以自定义实现健康检查类,比如自定义检测数据库或外部服务可用性的方法,如何实现呢?只需要实现系统内置的IHealthCheck接口,实现CheckHealthAsync(),如下代码所示:();if(canConnect)returnHealthCheckResult.Healthy();returnHealthCheckResult.Unhealthy();}}这里的IsDBOnline方法用于判断是否运行当前数据库状态,实现代码如下:privateboolIsDBOnline(){stringconnectionString="server=.;database=PYZ_L;Trusted_Connection=SSPI";try{using(SqlConnectionconnection=newSqlConnection(connectionString)){if(connection.State!=System.Data.ConnectionState.Open)connection.Open();}returntrue;}catch(System.Exception){returnfalse;}}然后在ConfigureServices方法中注入publicvoidConfigureServices(IServiceCollectionservices){services.AddControllersWithViews();services.AddHealthChecks().AddCheck("sqlcheck");}publicvoidConfigure(IApplicationBuilderapp,IWebHostEnvironmentenv){app.UseRouting().UseEndpoints(config=>{config.MapHealth("/health");});app.UseStaticFiles();app.UseRouting();app.UseEndpoints(endpoints=>{endpoints.MapControllerRoute(name:"default",pattern:"{controller=Home}/{action=Index}/{id?}");});}接下来可以浏览/health页面,可以看到端口自动执行了你的MyCustomHealthCheck方法,如下图:Checkingstrategy关于可视化健康检查虽然很好,但是没有很好的可视化解决方案。如果要实现可视化,需要单独下载Nuget包:AspNetCore.HealthChecks.UI、HealthChecks.UI.Client和AspNetCore.HealthChecks.UI.InMemory.Storage。命令如下:Install-PackageAspNetCore.HealthChecks.UIInstall-PackageAspNetCore.HealthChecks.UI.ClientInstall-PackageAspNetCore.HealthChecks.UI.InMemory.Storage安装包后,您可以在ConfigureServices和Configure方法下进行以下配置。publicclassStartup{//Thismethodgetscalledbytheruntime.Usethismethodtoaddservicestothecontainer.publicvoidConfigureServices(IServiceCollectionservices){services.AddControllersWithViews();services.AddHealthChecks();services.AddHealthChecksUI().AddInMemoryStorage();}//Thismethodgetscalledbytheruntime.UsethismethodtoconfiguretheHTTPrequestpipeline.publicvoidConfigure(IApplicationBuilderapp,IWebHostEnvironmentenv){app.UseRouting().UseEndpoints(config=>{config.MapHealthChecks("/health",newHealthCheckOptions{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"t;,"Microsoft":"警告","Microsoft.Hosting.Lifetime":"信息"}},"AllowedHosts":"*","HealthChecks-UI":{"HealthChecks":[{"名称":"Local","Uri":"http://localhost:65348/health"}],"EvaluationTimeOnSeconds":10,"MinimumSecondsBetweenFailureNotifications":60}}最后在浏览器中输入/healthchecks-ui可以看到长图UI如何使用ASP.NetCore的健康检查中间件非常方便的监控域外的系统资源、数据库或其他资源。您可以使用自定义检查逻辑来确定什么是Healthy什么是UnHealthy,值得一提的是,当检测到故障时,也可以使用故障通知机制,类似于githubreleasehook。翻译链接:https://www.infoworld.com/article/3379187/how-to-implement-health-checks-in-aspnet-core.html

最新推荐
猜你喜欢