Czytam książkę "ASP.NET Core 3 and Angular 9" i jest tam pokazane użycie Health Check z .NET Core (https://docs.microsoft.com/en-US/aspnet/core/host-and-deploy/health-checks?view=aspnetcore-3.0). Przykładowy kod z książki tworzy route /hc
po którego wywołaniu zostają zapingowane 3 adresy i jest zwracany json z wynikami - które adresy odpowiedziały szybko, a które wolno, albo wcale. Nie za bardzo rozumiem po co do tego celu używać tych Health Checków, skoro można stworzyć sobie controller z routem i tam zapingować co trzeba bez zaciągania jakichś dodatkowych namespace'ów. Ogólnie nie wiem jakie są plusy stosowania Microsoft.AspNetCore.Diagnostics.HealthChecks
. Czy mógłby ktoś podać jakieś zalety? A może ten przykład jest słaby?
Oto kod z książki"
Dodać do metody Configure
(Startup.cs):
app.UseHealthChecks("/hc", new CustomHealthCheckOptions());
Dodać do metody ConfigureServices
(Startup.cs):
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));
Nowy plik 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);
}
}
}
}
Nowy plik 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);
};
}
}
}