BootstrapAdmin/Bootstrap.Admin/HealthChecks/GiteeHttpHealthCheck.cs

53 lines
2.0 KiB
C#
Raw Normal View History

2019-08-13 15:55:55 +08:00
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using System;
using System.Collections.Generic;
using System.Diagnostics;
2019-08-14 11:05:59 +08:00
using System.Linq;
2019-08-13 15:55:55 +08:00
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Bootstrap.Admin.HealthChecks
{
/// <summary>
/// Gitee 接口检查器
/// </summary>
public class GiteeHttpHealthCheck : IHealthCheck
{
private readonly GiteeHttpClient _client;
2019-08-13 15:55:55 +08:00
/// <summary>
/// 构造函数
/// </summary>
/// <param name="client"></param>
2019-08-13 15:55:55 +08:00
/// <param name="accessor"></param>
public GiteeHttpHealthCheck(GiteeHttpClient client, IHttpContextAccessor accessor)
2019-08-13 15:55:55 +08:00
{
_client = client;
_client.HttpClient.BaseAddress = new Uri($"{accessor.HttpContext.Request.Scheme}://{accessor.HttpContext.Request.Host}{accessor.HttpContext.Request.PathBase}");
2019-08-13 15:55:55 +08:00
}
/// <summary>
/// 异步检查方法
/// </summary>
/// <param name="context"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
2019-08-14 11:05:59 +08:00
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
2019-08-13 15:55:55 +08:00
{
var urls = new string[] { "Issues", "Pulls", "Releases", "Builds" };
var data = new Dictionary<string, object>();
Task.WaitAll(urls.Select(url => Task.Run(async () =>
2019-08-13 15:55:55 +08:00
{
2019-08-14 11:05:59 +08:00
var sw = Stopwatch.StartNew();
Exception error = null;
var result = await _client.HttpClient.GetAsJsonAsync<object>($"/api/Gitee/{url}", ex => error = ex, cancellationToken);
sw.Stop();
data.Add(url, error == null ? $"{result} Elapsed: {sw.Elapsed}" : $"{result} Elapsed: {sw.Elapsed} Exception: {error}");
})).ToArray());
2019-08-14 11:05:59 +08:00
return Task.FromResult(HealthCheckResult.Healthy("Ok", data));
2019-08-13 15:55:55 +08:00
}
}
}