与仅在控制器路由中进行 ping 相比,使用 .NET Core 的中间件“运行状况检查”是否有优势?

Pio*_*rek 5 asp.net-core

我正在阅读一本“Asp.net Core 3 和 Angular 9”书,其中有一个 .NET Core 运行状况检查的示例用法。Microsoft 网站上也对此进行了描述:https://learn.microsoft.com/en-US/aspnet/core/host-and-deploy/health-checks ?view=aspnetcore-3.0 我找不到实际使用的理由它不仅仅是在某个控制器中创建一条将 ping 外部地址的路由。

书上的代码是这样的:

Configure在(Startup.cs) 方法中添加以下内容:

app.UseHealthChecks("/hc", new CustomHealthCheckOptions());
Run Code Online (Sandbox Code Playgroud)

ConfigureServices方法:

services.AddHealthChecks()
    .AddCheck("ICMP_01", new ICMPHealthCheck("www.ryadel.com", 100))
    .AddCheck("ICMP_02", new ICMPHealthCheck("www.google.com", 100))
    .AddCheck("ICMP_03", new ICMPHealthCheck("www.does-notexist.com", 100));
Run Code Online (Sandbox Code Playgroud)

创建 ICMPHealthCheck.cs 文件:

using Microsoft.Extensions.Diagnostics.HealthChecks;
using System;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;

namespace HealthCheck
{
    public class ICMPHealthCheck : IHealthCheck
    {
        private string Host { get; set; }
        private int Timeout { get; set; }

        public ICMPHealthCheck(string host, int timeout)
        {
            Host = host;
            Timeout = timeout;
        }

        public async Task<HealthCheckResult> CheckHealthAsync(
            HealthCheckContext context,
            CancellationToken cancellationToken = default)
        {
            try
            {
                using (var ping = new Ping())
                {
                    var reply = await ping.SendPingAsync(Host);

                    switch (reply.Status)
                    {
                        case IPStatus.Success:
                            var msg = String.Format(
                                "IMCP to {0} took {1} ms.",
                                Host,
                                reply.RoundtripTime);

                            return (reply.RoundtripTime > Timeout)
                            ? HealthCheckResult.Degraded(msg)
                            : HealthCheckResult.Healthy(msg);
                        default:
                            var err = String.Format(
                                "IMCP to {0} failed: {1}",
                                Host,
                                reply.Status);

                            return HealthCheckResult.Unhealthy(err);
                    }
                }
            }
            catch (Exception e)
            {
                var err = String.Format(
                    "IMCP to {0} failed: {1}",
                    Host,
                    e.Message);
                return HealthCheckResult.Unhealthy(err);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

创建 CustomHealthCheckOptions.cs 文件:

using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Http;
using System.Linq;
using System.Net.Mime;
using System.Text.Json;
namespace HealthCheck
{
    public class CustomHealthCheckOptions : HealthCheckOptions
    {
        public CustomHealthCheckOptions() : base()
        {
            var jsonSerializerOptions = new JsonSerializerOptions()
            {
                WriteIndented = true
            };
            ResponseWriter = async (c, r) =>
            {
                c.Response.ContentType =
                MediaTypeNames.Application.Json;
                c.Response.StatusCode = StatusCodes.Status200OK;
                var result = JsonSerializer.Serialize(new
                {
                    checks = r.Entries.Select(e => new
                    {
                        name = e.Key,
                        responseTime = e.Value.Duration.TotalMilliseconds,
                        status = e.Value.Status.ToString(),
                        description = e.Value.Description
                    }),
                    totalStatus = r.Status,
                    totalResponseTime =
                    r.TotalDuration.TotalMilliseconds,
                }, jsonSerializerOptions);
                await c.Response.WriteAsync(result);
            };
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

所以它只 ping 3 个地址,我看不到使用Microsoft.AspNetCore.Diagnostics.HealthChecks库的优势。这是错误的例子吗?