using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Data.Common; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.Extensions.Configuration; namespace Opsoft.NetCore.O3App.Shared.Data { public class DbConnectionFactory : IDbConnectionFactory { private ConcurrentDictionary _endpoints; private IConfiguration _configuration; private DiagnosticListener _listener = new DiagnosticListener("Opsoft.Data"); public DbConnectionFactory(IEnumerable providers, IConfiguration configuration) { _configuration = configuration; _endpoints = new ConcurrentDictionary(); foreach (IDbEndpointProvider provider in providers) { foreach (KeyValuePair endpoint in provider.GetEndpoints()) { if (_endpoints.ContainsKey(endpoint.Key)) { //sky.Error("数据库" + endpoint.Key + "配置重复设置,请检查相关配置!"); throw new InvalidOperationException("数据库" + endpoint.Key + "配置重复设置,请检查相关配置!"); } _endpoints.TryAdd(endpoint.Key, endpoint.Value); } provider.EndpointChanged += Provider_EndpointChanged; } DataSource.Endpoints = _endpoints; } private void Provider_EndpointChanged(object sender, EndpointChangedEventArgs e) { if (e == null) { return; } IDictionary changedEndpoints = e.ChangedEndpoints; IDictionary deleteEndpoints = e.DeleteEndpoints; if (deleteEndpoints != null && deleteEndpoints.Any()) { foreach (KeyValuePair item in deleteEndpoints) { _endpoints.TryRemove(item.Key, out var _); } } if (changedEndpoints == null || !changedEndpoints.Any()) { return; } foreach (KeyValuePair optionSet in changedEndpoints) { _endpoints.AddOrUpdate(optionSet.Key, optionSet.Value, (string dbName, DbEndpoint dbEndpoint) => optionSet.Value); } } public DbConnection GetConnection(string dbName, bool readOnly = true, bool checkWhere = false) { if (!_endpoints.TryGetValue(dbName, out var value)) { //Log.Error("无法找到数据库名为" + dbName + "的对应的ConnectionFactory,请检查配置是否正确"); throw new InvalidOperationException("无法找到数据库名为" + dbName + "的对应的ConnectionFactory,请检查配置是否正确"); } if (value.DatabaseOptions != null) { ConnectionOptions readConnectionConfig = GetReadConnectionConfig(value.DatabaseOptions); ConnectionOptions writeConnectionConfig = GetWriteConnectionConfig(value.DatabaseOptions); IConnectionFactory connectionFactory = null; string text = null; bool passwordEncrypted = false; string text2 = null; if (readOnly) { if (readConnectionConfig != null) { IConnectionFactory byProvider = ConnectionFactory.Instance.GetByProvider(readConnectionConfig.Provider); passwordEncrypted = readConnectionConfig.PasswordEncrypted; text = readConnectionConfig.ConnectionString; text2 = readConnectionConfig.Provider; connectionFactory = byProvider; } } else if (writeConnectionConfig != null) { IConnectionFactory byProvider2 = ConnectionFactory.Instance.GetByProvider(writeConnectionConfig.Provider); passwordEncrypted = writeConnectionConfig.PasswordEncrypted; text = writeConnectionConfig.ConnectionString; text2 = writeConnectionConfig.Provider; connectionFactory = byProvider2; } if (connectionFactory == null || string.IsNullOrWhiteSpace(text) || string.IsNullOrWhiteSpace(text2)) { //Log.Error("无法找到匹配的数据库连接,请求的数据库是" + dbName + ",请求的数据库类型为" + (readOnly ? "读库" : "写库")); throw new InvalidOperationException("无法找到匹配的数据库连接,请求的数据库是" + dbName + ",请求的数据库类型为" + (readOnly ? "读库" : "写库")); } string appUK = _configuration["APP_UK"]; return CreateConenction(connectionFactory, text, passwordEncrypted, appUK, text2, checkWhere, _listener); } IConnectionFactory connectionFactory2; string text3; bool passwordEncrypted2; string text4; if (readOnly) { connectionFactory2 = value.ReadConnectionFactory; text3 = value.ReadConnectionString; passwordEncrypted2 = value.ReadPasswordEncrypted; text4 = value.ReadProvider; } else { connectionFactory2 = value.WriteConnectionFactory; text3 = value.WriteConnectionString; passwordEncrypted2 = value.WritePasswordEncrypted; text4 = value.WriteProvider; } if (connectionFactory2 == null || string.IsNullOrWhiteSpace(text3) || string.IsNullOrWhiteSpace(text4)) { //Log.Error("无法找到匹配的数据库连接,请求的数据库是" + dbName + ",请求的数据库类型为" + (readOnly ? "读库" : "写库")); throw new InvalidOperationException("无法找到匹配的数据库连接,请求的数据库是" + dbName + ",请求的数据库类型为" + (readOnly ? "读库" : "写库")); } return CreateConenction(connectionFactory2, text3, passwordEncrypted2, value.AppUK, text4, checkWhere, _listener); } private DbConnection CreateConenction(IConnectionFactory connectionFactory, string connectionString, bool passwordEncrypted, string appUK, string provider, bool checkWhere, DiagnosticSource listener) { DbConnectionStringBuilder dbConnectionStringBuilder = connectionFactory.CreateConnectionStringBuilder(connectionString); if (passwordEncrypted) { string toDecrypt = (string)dbConnectionStringBuilder["Password"]; //try //{ // toDecrypt = Security.Decrypt(toDecrypt, GetSecurity(appUK)); //} //catch (Exception ex) //{ // Log.Error(ex, "Decrypt password error"); // throw new ArgumentException("Decrypt password error", ex); //} dbConnectionStringBuilder["Password"] = toDecrypt; } dbConnectionStringBuilder["PersistSecurityInfo"] = bool.FalseString; OPDbConnection tCDbConnection = new OPDbConnection(connectionFactory.CreateConnection(dbConnectionStringBuilder), checkWhere, provider, listener); dbConnectionStringBuilder["Password"] = "WARNING:You shouldn't use ConnectionString directly!"; dbConnectionStringBuilder["PersistSecurityInfo"] = bool.TrueString; tCDbConnection.ConnectionString = dbConnectionStringBuilder.ConnectionString; return tCDbConnection; } private string GetSecurity(string appUK) { if (appUK.Length < 16) { return appUK.PadRight(16, '0'); } if (appUK.Length > 16) { return appUK.Substring(0, 16); } return appUK; } public void Set(string dbName, string connectionString, DbProvider dbProvider) { string provider = GetProvider(dbProvider); IConnectionFactory byProvider = ConnectionFactory.Instance.GetByProvider(provider); IConnectionFactory byProvider2 = ConnectionFactory.Instance.GetByProvider(provider); DbEndpoint dbEndpoint = new DbEndpoint { ReadConnectionFactory = byProvider, ReadConnectionString = connectionString, ReadProvider = provider, WriteConnectionFactory = byProvider2, WriteConnectionString = connectionString, WriteProvider = provider }; _endpoints.AddOrUpdate(dbName, dbEndpoint, (string databaseName, DbEndpoint databaseEndpoint) => dbEndpoint); } public void Set(string dbName, string readConnectionString, DbProvider readDbProvider, string writeConnectionString, DbProvider writeDbProvider) { string provider = GetProvider(readDbProvider); string provider2 = GetProvider(writeDbProvider); IConnectionFactory byProvider = ConnectionFactory.Instance.GetByProvider(provider); IConnectionFactory byProvider2 = ConnectionFactory.Instance.GetByProvider(provider2); DbEndpoint dbEndpoint = new DbEndpoint { ReadConnectionFactory = byProvider, ReadConnectionString = readConnectionString, ReadProvider = provider, WriteConnectionFactory = byProvider2, WriteConnectionString = writeConnectionString, WriteProvider = provider2 }; _endpoints.AddOrUpdate(dbName, dbEndpoint, (string databaseName, DbEndpoint databaseEndpoint) => dbEndpoint); } public void UnSet(string dbName) { _endpoints.TryRemove(dbName, out var _); } private string GetProvider(DbProvider dbProvider) { string empty = string.Empty; switch (dbProvider) { case DbProvider.SQLServerProviderName: return "System.Data.SqlClient"; case DbProvider.MySQLProviderName: return "MySql.Data.MySqlClient"; case DbProvider.PostgreSQLProviderName: return "Npgsql"; default: //Log.Error("provider不在服务提供范围内"); throw new ArgumentException("provider不在服务提供范围内"); } } private static ConnectionOptions GetReadConnectionConfig(DatabaseOptions databaseConfig) { if (databaseConfig.ReadConnections.Count < 2) { return databaseConfig.ReadConnections.FirstOrDefault(); } int num = Interlocked.Increment(ref databaseConfig.ReadSeed); int num2 = RoundRobin(databaseConfig.ReadConnections, num); if (num2 < num) { Interlocked.CompareExchange(ref databaseConfig.ReadSeed, num2, num); } return databaseConfig.ReadConnections[num2]; } private static ConnectionOptions GetWriteConnectionConfig(DatabaseOptions databaseConfig) { if (databaseConfig.WriteConnections.Count < 2) { return databaseConfig.WriteConnections.FirstOrDefault(); } int num = Interlocked.Increment(ref databaseConfig.WriteSeed); int num2 = RoundRobin(databaseConfig.WriteConnections, num); if (num2 < num) { Interlocked.CompareExchange(ref databaseConfig.WriteSeed, num2, num); } return databaseConfig.WriteConnections[num2]; } private static int RoundRobin(List connectionConfigs, int seed) { return seed % connectionConfigs.Count; } } }