BootstrapAdmin/Bootstrap.Admin/HealthChecks/GiteeHttpHealthCheck.cs

63 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 HttpClient _client;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="factory"></param>
/// <param name="accessor"></param>
public GiteeHttpHealthCheck(IHttpClientFactory factory, IHttpContextAccessor accessor)
{
_client = factory.CreateClient();
2019-08-14 11:05:59 +08:00
_client.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>();
2019-08-14 11:05:59 +08:00
urls.ToList().ForEach(url =>
2019-08-13 15:55:55 +08:00
{
2019-08-14 11:05:59 +08:00
var sw = Stopwatch.StartNew();
try
{
var task = _client.GetStringAsync($"/api/Gitee/{url}");
task.Wait(cancellationToken);
}
catch (Exception)
{
2019-08-13 15:55:55 +08:00
2019-08-14 11:05:59 +08:00
}
finally
{
sw.Stop();
data.Add(url, sw.Elapsed);
}
});
return Task.FromResult(HealthCheckResult.Healthy("Ok", data));
2019-08-13 15:55:55 +08:00
}
}
}