詳解如何在ASP.Net Core中實現健康檢查
健康檢查
常用於判斷一個應用程式能否對 request 請求進行響應,ASP.Net Core 2.2 中引入了 健康檢查
中介軟體用於報告應用程式的健康狀態。
ASP.Net Core 中的 健康檢查
落地做法是暴露一個可配置的 Http 埠,你可以使用 健康檢查
去做一個最簡單的活性檢測,比如說:檢查網路和系統的資源可用性,資料庫資源是否可用,應用程式依賴的訊息中介軟體或vsSUf者 Azure cloud service 的可用性 等等,這篇文章我們就來討論如何使用這個 健康檢查中介軟體。
註冊健康檢查服務
要註冊 健康檢查
服務,需要在 Startup.ConfigureServices
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(connectionStrhttp://www.cppcns.coming)) { 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.Client
和 AspNetCore.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": { "Dewww.cppcns.comfault": "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,值得一提的是,當檢測到失敗時還可以使用失http://www.cppcns.com敗通知機制,類似 github 釋出鉤子。
譯文連結:https://www.infoworld.com/article/3379187/how-to-implement-health-checks-in-aspnet-core.html
到此這篇關於詳解如何在ASP.Net Core中實現健康檢查的文章就介紹到這了,更多相關ASP.Net Core 健康檢查內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!