自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

如何在 ASP.Net Core 中實現(xiàn)健康檢查

開發(fā) 前端
健康檢查 常用于判斷一個應(yīng)用程序能否對 request 請求進行響應(yīng),ASP.Net Core 2.2 中引入了 健康檢查 中間件用于報告應(yīng)用程序的健康狀態(tài)。

[[376036]]

本文轉(zhuǎn)載自微信公眾號「碼農(nóng)讀書」,作者碼農(nóng)讀書 。轉(zhuǎn)載本文請聯(lián)系碼農(nóng)讀書公眾號。

健康檢查 常用于判斷一個應(yīng)用程序能否對 request 請求進行響應(yīng),ASP.Net Core 2.2 中引入了 健康檢查 中間件用于報告應(yīng)用程序的健康狀態(tài)。

ASP.Net Core 中的 健康檢查 落地做法是暴露一個可配置的 Http 端口,你可以使用 健康檢查 去做一個最簡單的活性檢測,比如說:檢查網(wǎng)絡(luò)和系統(tǒng)的資源可用性,數(shù)據(jù)庫資源是否可用,應(yīng)用程序依賴的消息中間件或者 Azure cloud service 的可用性 等等,這篇文章我們就來討論如何使用這個 健康檢查中間件。

注冊健康檢查服務(wù)

要注冊 健康檢查 服務(wù),需要在 Startup.ConfigureServices 下調(diào)用 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 是否存活的暴露端口。

其他服務(wù)的健康檢查

除了web的活性檢查,還可以檢查諸如:SQL Server, MySQL, MongoDB, Redis, RabbitMQ, Elasticsearch, Hangfire, Kafka, Oracle, Azure Storage 等一系列服務(wù)應(yīng)用的活性,每一個服務(wù)需要引用相關(guān)的 nuget 包即可,如下圖所示:

然后在 ConfigureServices 中添加相關(guān)服務(wù)即可,比如下面代碼的 AddSqlServer。

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

自定義健康檢查

除了上面的一些開源方案,還可以自定義實現(xiàn) 健康檢查 類,比如自定義方式來檢測 數(shù)據(jù)庫 或 外部服務(wù) 的可用性,那怎么實現(xiàn)呢?只需要實現(xiàn)系統(tǒng)內(nèi)置的 IHealthCheck 接口并實現(xiàn) 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 方法用來判斷當前數(shù)據(jù)庫是否是運行狀態(tài),實現(xiàn)代碼如下:

  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 頁面,可以看出該端口自動執(zhí)行了你的 MyCustomHealthCheck 方法,如下圖所示:

可視化健康檢查

上面的檢查策略雖然好,但并沒有一個好的可視化方案,要想實現(xiàn)可視化的話,還需要單獨下載 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 的 健康檢查中間件 可以非常方便的對 系統(tǒng)資源,數(shù)據(jù)庫 或者其他域外資源進行監(jiān)控,你可以使用自定義檢查邏輯來判斷什么樣的情況算是 Healthy,什么樣的算是 UnHealthy,值得一提的是,當檢測到失敗時還可以使用失敗通知機制,類似 github 發(fā)布鉤子。

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

責任編輯:武曉燕 來源: 碼農(nóng)讀書
相關(guān)推薦

2021-01-13 07:33:41

API數(shù)據(jù)安全

2021-11-01 14:52:38

ElasticSear索引SQL

2021-03-17 09:45:31

LazyCacheWindows

2021-02-02 16:19:08

Serilog日志框架

2021-02-06 21:40:13

SignalR通訊TypeScript

2021-01-31 22:56:50

FromServiceASP

2021-02-03 13:35:25

ASPweb程序

2021-03-03 22:37:16

MediatR中介者模式

2021-03-10 09:40:43

LamarASP容器

2021-02-28 20:56:37

NCache緩存框架

2021-01-28 22:39:35

LoggerMessa開源框架

2021-01-07 07:39:07

工具接口 Swagger

2021-03-18 07:33:54

PDF DinkToPdfC++

2021-02-07 17:29:04

監(jiān)視文件接口

2021-01-11 05:20:05

Controller代碼數(shù)據(jù)層

2023-03-02 07:20:10

GRPC服務(wù)健康檢查協(xié)議

2023-03-03 08:19:35

KubernetesgRPC

2021-03-08 07:32:05

Actionweb框架

2009-08-05 11:00:46

獲得RowIndexASP.NET

2021-01-05 07:51:06

版本化ASP
點贊
收藏

51CTO技術(shù)棧公眾號