-
Notifications
You must be signed in to change notification settings - Fork 0
/
UrlHealthCheck.cs
85 lines (81 loc) · 3.14 KB
/
UrlHealthCheck.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace NetPro.Checker
{
public class UrlHealthCheck : IHealthCheck
{
private readonly List<string> _urls;
private static HttpClient _httpclient;
private readonly List<HttpStatusCode> _statusCodes;
public UrlHealthCheck(List<string> urls, List<HttpStatusCode> statusCodes)
{
_httpclient = new HttpClient();
_urls = urls;
_statusCodes = statusCodes;
}
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
List<string> message = new List<string>();
List<string> exception = new List<string>();
foreach (var item in _urls)
{
try
{
var result = await _httpclient.GetAsync(item);
if (!_statusCodes.Contains(result.StatusCode))
{
message.Add($"[{item}] StatusCode is `[{result.StatusCode}]`,request exception");
}
}
catch (Exception ex)
{
exception.Add($"[{item}]Exception is ----->[{ex.Message}]");
}
}
if (exception.Any())
{
return new HealthCheckResult(context.Registration.FailureStatus, exception: new Exception(string.Join(',', exception)));
}
if (message.Any())
{
return new HealthCheckResult(context.Registration.FailureStatus, string.Join("--------", message));
}
return HealthCheckResult.Healthy();
}
}
public static class HealthChecksUrlExtensions
{
private static readonly string NAME = "urlcheck";
/// <summary>
///
/// </summary>
/// <param name="builder"></param>
/// <param name="urls"></param>
/// <param name="succeedtatusCodes">default is HttpStatusCode.OK </param>
/// <param name="name"></param>
/// <param name="failureStatus"></param>
/// <param name="tags"></param>
/// <param name="timeout"></param>
/// <returns></returns>
public static IHealthChecksBuilder AddUrl(this IHealthChecksBuilder builder, List<string> urls, List<HttpStatusCode> succeedtatusCodes = null, string name = default, HealthStatus? failureStatus = default, IEnumerable<string> tags = default, TimeSpan? timeout = default)
{
if (succeedtatusCodes == null)
{
succeedtatusCodes = new List<HttpStatusCode>() { HttpStatusCode.OK };
}
return builder.Add(new HealthCheckRegistration(
name ?? NAME,
sp => new UrlHealthCheck(urls, succeedtatusCodes),
failureStatus,
tags,
timeout));
}
}
}