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
|
|
|
|
|
{
|
2019-08-14 17:19:00 +08:00
|
|
|
|
private readonly GiteeHttpClient _client;
|
2019-08-13 15:55:55 +08:00
|
|
|
|
/// <summary>
|
|
|
|
|
/// 构造函数
|
|
|
|
|
/// </summary>
|
2019-08-14 17:19:00 +08:00
|
|
|
|
/// <param name="client"></param>
|
2019-08-13 15:55:55 +08:00
|
|
|
|
/// <param name="accessor"></param>
|
2019-08-14 17:19:00 +08:00
|
|
|
|
public GiteeHttpHealthCheck(GiteeHttpClient client, IHttpContextAccessor accessor)
|
2019-08-13 15:55:55 +08:00
|
|
|
|
{
|
2019-08-14 17:19:00 +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>();
|
|
|
|
|
|
2019-08-14 11:22:24 +08:00
|
|
|
|
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();
|
2019-08-14 11:22:24 +08:00
|
|
|
|
Exception error = null;
|
2019-08-14 17:19:00 +08:00
|
|
|
|
var result = await _client.HttpClient.GetAsJsonAsync<object>($"/api/Gitee/{url}", ex => error = ex, cancellationToken);
|
2019-08-14 11:22:24 +08:00
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|