52 lines
1.7 KiB
C#
52 lines
1.7 KiB
C#
|
|
using Microsoft.Data.SqlClient;
|
||
|
|
|
||
|
|
namespace YY.Admin.Services.Service.EquipmentDb;
|
||
|
|
|
||
|
|
public interface IEquipmentDbConnectionFactory
|
||
|
|
{
|
||
|
|
SqlConnection CreateConnection();
|
||
|
|
Task<(bool Ok, string Message)> TestAsync(CancellationToken cancellationToken = default);
|
||
|
|
EquipmentDbSettingsStore.EquipmentDbSettings CurrentSettings { get; }
|
||
|
|
void Reload();
|
||
|
|
}
|
||
|
|
|
||
|
|
public sealed class EquipmentDbConnectionFactory : IEquipmentDbConnectionFactory
|
||
|
|
{
|
||
|
|
private EquipmentDbSettingsStore.EquipmentDbSettings _settings = EquipmentDbSettingsStore.Load();
|
||
|
|
|
||
|
|
public EquipmentDbSettingsStore.EquipmentDbSettings CurrentSettings => _settings;
|
||
|
|
|
||
|
|
public void Reload()
|
||
|
|
{
|
||
|
|
_settings = EquipmentDbSettingsStore.Load();
|
||
|
|
}
|
||
|
|
|
||
|
|
public SqlConnection CreateConnection()
|
||
|
|
{
|
||
|
|
if (!_settings.Enabled)
|
||
|
|
{
|
||
|
|
throw new InvalidOperationException("设备库连接未启用");
|
||
|
|
}
|
||
|
|
return new SqlConnection(EquipmentDbSettingsStore.BuildConnectionString(_settings));
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task<(bool Ok, string Message)> TestAsync(CancellationToken cancellationToken = default)
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
Reload();
|
||
|
|
await using var conn = CreateConnection();
|
||
|
|
await conn.OpenAsync(cancellationToken).ConfigureAwait(false);
|
||
|
|
await using var cmd = conn.CreateCommand();
|
||
|
|
cmd.CommandText = "SELECT 1";
|
||
|
|
cmd.CommandTimeout = Math.Max(5, _settings.ConnectTimeoutSeconds);
|
||
|
|
var scalar = await cmd.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false);
|
||
|
|
return (true, "连接成功: " + scalar);
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
return (false, ex.Message);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|