/// <summary> /// 构造 /// </summary> /// <param name="context"></param> public Qt2Api(UserContext context) { _token = context?.Token; _baseUrl = ServerSetting.GetConstValue("HttpProxy")?.Value; if (string.IsNullOrEmpty(_baseUrl)) { logger.LogError("服务没有配置HttpProxy常量,默认设置为开发版api网关地址!"); _baseUrl = "http://192.168.100.121/api/"; } }
/// <summary> /// 这里需要定时清理不用的连接 /// </summary> private static void Clear() { while (true) { try { string[] key = ConnectionPools.Keys.ToArray(); if (key.Length > 0) { // 为了保证性能,随机检查,不做全量遍历 Random random = new Random(DateTime.Now.Millisecond); int idx = random.Next(0, key.Length); lock (root) { if (ConnectionPools.ContainsKey(key[idx])) { var lst = ConnectionPools[key[idx]]; // 连接池里面里连接大于1的时候才会清理,防止清空了就起不到连接池的作用了 if (lst.Count > 1) { // 2分钟不被使用,就清理掉 var timeOut = lst.Where(a => DateTime.Now.Subtract(a.V1).TotalSeconds > 60 * 2) .ToArray(); foreach (var item in timeOut) { // 始终保持有1个,超时也不能清空 if (lst.Count > 1) { // 把超时的移除掉 , 释放掉连接 lst.Remove(item); item.V2.Close(); } } } } } } } catch (Exception ex) { logger.LogError(ex, "ClientConnectionManager.Clear.Error"); } var rpcSocketIntervalTime = ServerSetting.GetConstValue("RpcSocketRecycleIntervalMin")?.Value; int timeSpan = 0; int.TryParse(rpcSocketIntervalTime ?? "3", out timeSpan); if (timeSpan < 1) { timeSpan = 3; } // 3分钟检查一次,这里只是为了防止连接长期防止缓存池,检查频度不要求太高(2分钟过期+3分钟检查间隔其实就是5分钟) Thread.Sleep(timeSpan * 60 * 1000); } }
public static IEFDbContext GetEFContext <TContext>(RpcContext rpcContext) where TContext : DbContext { var dbName = typeof(TContext).Name.ToLower(); var info = DBContextOptionsLoader.IsMemoryDb ? new DbInfo() : GetDbInfo(rpcContext, dbName); var options = DBContextOptionsLoader.CreateDbOption <TContext>(info); if (ServerSetting.GetConstValue("TrackSql")?.Value.ToLower() == "true") { options.UseLoggerFactory(LogFactory.LoggerFactory); } var dbContext = (TContext)Activator.CreateInstance(typeof(TContext), options.Options); return(new EFDbContext(dbContext, info)); }
public static void Init() { var bAudit = ServerSetting.GetConstValue("IsAudit")?.Value ?? "true"; if (bAudit.ToLower() == "true") { GrantDBContext.OnQtDapperCommit += GrantDBContext_OnQtDapperCommit; GrantDBContext.OnQtEFCommit += GrantDBContext_OnQtEFCommit; } //初始化过滤审计内容 AuditManager.DefaultConfiguration.IgnoreRelationshipAdded = true; AuditManager.DefaultConfiguration.IgnoreEntityAdded = true; AuditManager.DefaultConfiguration.IgnoreEntitySoftAdded = true; AuditManager.DefaultConfiguration.IgnoreEntitySoftDeleted = true; }
private void PrintSql(string sql, object param) { try { if (ServerSetting.GetConstValue("TrackSql")?.Value.ToLower() == "true") { StringBuilder sb = new StringBuilder(); sb.AppendLine("TrackSql=" + sql); sb.AppendLine(JsonEx.JsonConvert.JsonSerializer(param)); logger.LogInformation(sb.ToString()); } } catch (Exception ex) { //打印SQL异常时不影响业务 } }
/// <summary> /// 创建DbContext 构造参数 /// </summary> /// <returns></returns> public static DbContextOptions <T> CreateMySqlDbOption <T>(string ip, string uName, string uPwd, string dbName, string port = "3306") where T : DbContext { ////这里通过登录用户构建 connection var sqlConnectionString = $"Data Source={ip};port={port};Initial Catalog={dbName};user id={uName};password={uPwd};Character Set=utf8;Allow Zero Datetime=true;Convert Zero Datetime=true;pooling=true;MaximumPoolsize=100;"; DbContextOptionsBuilder <T> options = new DbContextOptionsBuilder <T>(); // 使用Console Debug EF Sql if (ServerSetting.GetConstValue("TrackSql")?.Value.ToLower() == "true") { options.UseLoggerFactory(LogFactory.LoggerFactory); } options.UseMySql(sqlConnectionString); return(options.Options); }
private void PrintSql(string sql, DynamicParameters ps) { try { if (ServerSetting.GetConstValue("TrackSql")?.Value.ToLower() == "true") { StringBuilder sb = new StringBuilder(); sb.AppendLine("TrackSql=" + sql); ps?.ParameterNames?.ToList()?.ForEach(x => { sb.AppendLine($"{x}={ps.Get<object>(x)}"); }); logger.LogInformation(sb.ToString()); } } catch (Exception ex) { //打印SQL异常时不影响业务 } }
public static IGrantEFDbContext GetEFContext <TContext>(RpcContext rpcContext) where TContext : DbContext { var dbName = typeof(TContext).Name.ToLower(); var info = DBContextOptionsLoader.IsMemoryDb ? new DbInfo() : GetDbInfo(rpcContext, dbName); var options = DBContextOptionsLoader.CreateDbOption <TContext>(info); if (ServerSetting.GetConstValue("TrackSql")?.Value.ToLower() == "true") { options.UseLoggerFactory(LogFactory.LoggerFactory); } var dbContext = (TContext)Activator.CreateInstance(typeof(TContext), options.Options); return(new GrantEFDbContext(dbContext, info)); //if (OnQtEFCommit != null) //{ // ctx.OnDbCommit += (DbContext dbCtx, Z.EntityFramework.Plus.Audit audit) => { // OnQtEFCommit.Invoke(rpcContext, dbCtx, info, audit); // }; //} //return ctx; }
private static DbInfo GetDbInfo(RpcContext rpcContext, string dbName) { try { // 先找用户私有化的配置 var sysInfos = rpcContext.GetUserContext()?.GetSysInfo(); if (sysInfos == null || !sysInfos.Any()) { if (!string.IsNullOrEmpty(rpcContext.Args.tk)) { logger.LogWarning("GrantDBContext.GetDbInfo.GetUserCtx.sysInfos==null"); } } var dbInfos = sysInfos?.Where(a => a.DbModelName?.ToLower() == dbName).ToList(); ConstItem dbValue = null; if (dbInfos == null || !dbInfos.Any()) { // 从配置文件做了兼容转换,等数据库tenant_database的DBModelName字段启用后就直接能取到了 dbValue = ServerSetting.GetConstValue(dbName); if (dbValue != null) { var sysId = dbValue.Value.ToLower(); dbInfos = sysInfos.Where(a => a.SysID?.ToLower() == sysId && !string.IsNullOrEmpty(a.DBIP)).ToList(); } } DbInfo info = null; if (dbInfos != null && dbInfos.Any()) { var dbInfo = dbInfos.First(); var dbType = dbInfo.DBType; DbType dType = DbTypeParser.Parser(dbType); info = new DbInfo() { DbType = dType, DbName = dbInfo.DBName, Ip = dbInfo.DBIP, Port = dbInfo.DbPort, UserName = dbInfo.DBUser, Pwd = dbInfo.DBPwd, DbContextName = dbName, }; } else { // 如果私有化的表没有,找全局的表 var dbModel = ServerSetting.GetDbModelContext(dbName); if (dbModel == null) { throw new Exception($"DataModel Info :{dbName} Is Not Found"); } DbType dType = DbTypeParser.Parser(dbModel.DbType); // 需要根据接口配置的主从来选择主从,这里先暂时全部取主,有空了在完善接口主从配置 info = new DbInfo() { DbName = dbModel.Database, DbType = dType, Ip = dbModel.Master.Ip, Port = dbModel.Master.Port, UserName = dbModel.UserName, Pwd = dbModel.PassWord, DbContextName = dbName, }; } logger.LogDebug($"获取的数据库信息是:{info?.ToString()}"); return(info); } catch (Exception e) { logger.LogCritical(e, $"GrantDBContext.GetDbInfo.Error,获取数据库{dbName}连接信息异常"); throw new BusinessException(new StatusCode(StatusCode.ServerError.code, $"无法找到用户的数据库信息,请检查租户数据库,或者Config目录下的数据库配置信息({dbName})")); } }