fix: 数据库健康检查支持 MongoDB

This commit is contained in:
Argo Zhang 2019-08-23 22:33:44 +08:00
parent 217af27c41
commit 1cf5de03ec
1 changed files with 32 additions and 12 deletions

View File

@ -1,6 +1,7 @@
using Bootstrap.DataAccess; using Bootstrap.DataAccess;
using Bootstrap.Security; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Diagnostics.HealthChecks;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
@ -14,6 +15,20 @@ namespace Bootstrap.Admin.HealthChecks
/// </summary> /// </summary>
public class DBHealthCheck : IHealthCheck public class DBHealthCheck : IHealthCheck
{ {
private IConfiguration _configuration;
private static readonly Func<IConfiguration, string, string> ConnectionStringResolve = (c, name) => string.IsNullOrEmpty(name)
? c.GetSection("ConnectionStrings").GetChildren().FirstOrDefault()?.Value
: c.GetConnectionString(name);
/// <summary>
/// 构造函数
/// </summary>
/// <param name="configuration"></param>
public DBHealthCheck(IConfiguration configuration)
{
_configuration = configuration;
}
/// <summary> /// <summary>
/// 异步检查方法 /// 异步检查方法
/// </summary> /// </summary>
@ -22,18 +37,23 @@ namespace Bootstrap.Admin.HealthChecks
/// <returns></returns> /// <returns></returns>
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{ {
using (var db = DbManager.Create()) var db = _configuration.GetSection("DB").GetChildren()
.Select(config => new
{ {
var connStr = db.ConnectionString; Enabled = bool.TryParse(config["Enabled"], out var en) ? en : false,
var dicts = db.Fetch<BootstrapDict>("Select * from Dicts"); ProviderName = config["ProviderName"],
Widget = config["Widget"],
ConnectionString = ConnectionStringResolve(config.GetSection("ConnectionStrings").Exists() ? config : _configuration, string.Empty)
}).FirstOrDefault(i => i.Enabled);
var dicts = DictHelper.RetrieveDicts();
var data = new Dictionary<string, object>() var data = new Dictionary<string, object>()
{ {
{ "ConnectionString", connStr }, { "ConnectionString", db.ConnectionString },
{ "DbType", db.Provider.GetType().Name }, { "Widget", db.Widget },
{ "Dicts", dicts.Count } { "DbType", db.ProviderName },
{ "Dicts", dicts.Count() }
}; };
return dicts.Any() ? Task.FromResult(HealthCheckResult.Healthy("Ok", data)) : Task.FromResult(HealthCheckResult.Degraded("No init data in DB")); return dicts.Any() ? Task.FromResult(HealthCheckResult.Healthy("Ok", data)) : Task.FromResult(HealthCheckResult.Degraded("No init data in DB"));
} }
} }
} }
}