[SqlSugar] 一定时间web页面不操作后报错 返回
SqlSugar
沟通中
5
550

悬赏:0 飞吻
问题:
目前不清楚是偶发性问题还是其他问题,项目是从以前SqlServer数据库改为mysql8.0,我自己在开发使用中并没触发过这个错误,但是听测试说经常会出现,特别是当页面不操作(没有请求数据)一段时间后(一小时左右)就会出现
错误日志:
数据库连接错误 at SqlSugar.SqlSugarRepository`1..ctor(IServiceProvider serviceProvider, ISqlSugarClient context) at ResolveService(ILEmitResolverBuilderRuntimeContext , ServiceProviderEngineScope ) at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope) at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired) at lambda_method598(Closure , IServiceProvider , Object[] ) at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass6_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextExceptionFilterAsync>g__Awaited|26_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) System.Reflection.ParameterInfo[]
SqlSugar版本:Version=3.4.7.0
数据库连接字符串:server=xxxx;Port=xxxx;Database=xxxx;Uid=xxxx;Pwd=xxxx;AllowLoadLocalInfile=true;SslMode=none;AllowPublicKeyRetrieval=True;
SqlSugar配置:
public static void SqlSugarConfigure(this IServiceCollection services) { // 获取选项 var dbOptions = App.GetOptions<ConnectionStringsOptions>(); dbOptions.ConnectionConfigs.ForEach(SetDbConfig); List<ConnectionConfig> connectConfigList = new List<ConnectionConfig>(); var conns = dbOptions.ConnectionConfigs.Select(s => new ConnectionConfig { AopEvents = s.AopEvents, ConfigId = s.ConfigId, ConnectionString = s.ConnectionString, DbLinkName = s.DbLinkName, DbType = s.DbType, IndexSuffix = s.IndexSuffix, IsAutoCloseConnection = s.IsAutoCloseConnection, LanguageType = s.LanguageType, MoreSettings = s.MoreSettings, SlaveConnectionConfigs = s.SlaveConnectionConfigs, SqlMiddle = s.SqlMiddle }).ToList(); SqlSugarScope sqlSugar = new(conns, db => { dbOptions.ConnectionConfigs.ForEach(config => { var dbProvider = db.GetConnectionScope(config.ConfigId); SetDbAop(dbProvider); }); }); services.AddSingleton<ISqlSugarClient>(sqlSugar); // 单例注册 services.AddScoped(typeof(ISqlSugarRepository<>), typeof(SqlSugarRepository<>)); // 仓储注册 services.AddUnitOfWork<SqlSugarUnitOfWork>(); // 事务与工作单元注册 } /// <summary> /// 配置连接属性. /// </summary> /// <param name="config"></param> private static void SetDbConfig(DbConnectionConfig config) { config.ConnectionString = string.Format(config.DefaultConnection, config.DBName); config.ConfigureExternalServices = new ConfigureExternalServices { EntityService = (type, column) => // 处理列 { if (column.IsPrimarykey == false && new NullabilityInfoContext().Create(type).WriteState is NullabilityState.Nullable) column.IsNullable = true; if (config.DbType == SqlSugar.DbType.Oracle) { if (type.PropertyType == typeof(long) || type.PropertyType == typeof(long?)) column.DataType = "number(18)"; if (type.PropertyType == typeof(bool) || type.PropertyType == typeof(bool?)) column.DataType = "number(1)"; } }, }; config.IsAutoCloseConnection = true; config.MoreSettings = new ConnMoreSettings { IsAutoRemoveDataCache = true, SqlServerCodeFirstNvarchar = true // 采用Nvarchar }; } /// <summary> /// 配置Aop. /// </summary> /// <param name="db"></param> public static void SetDbAop(SqlSugarScopeProvider db) { var config = db.CurrentConnectionConfig; // 设置超时时间 db.Ado.CommandTimeOut = 30; // 打印SQL语句 db.Aop.OnLogExecuting = (sql, pars) => { var originColor = Console.ForegroundColor; if (sql.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase)) Console.ForegroundColor = ConsoleColor.Green; if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase)) Console.ForegroundColor = ConsoleColor.Yellow; if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase)) Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("【" + DateTime.Now + "——执行SQL】\r\n" + UtilMethods.GetSqlString(config.DbType, sql, pars) + "\r\n"); Console.ForegroundColor = originColor; App.PrintToMiniProfiler("SqlSugar", "Info", sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value))); }; db.Aop.OnError = ex => { if (ex.Parametres == null) return; var originColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.DarkRed; var pars = db.Utilities.SerializeObject(((SugarParameter[])ex.Parametres).ToDictionary(it => it.ParameterName, it => it.Value)); Console.WriteLine("【" + DateTime.Now + "——错误SQL】\r\n" + UtilMethods.GetSqlString(config.DbType, ex.Sql, (SugarParameter[])ex.Parametres) + "\r\n"); Console.ForegroundColor = originColor; App.PrintToMiniProfiler("SqlSugar", "Error", $"{ex.Message}{Environment.NewLine}{ex.Sql}{pars}{Environment.NewLine}"); }; //配置 差异日志功能 功能,记录差异化日志,需要在SqlSugar语句末尾加上 .EnableDiffLogEvent() 方法 db.Aop.OnDiffLogEvent = it => { string requestMethod = "其他"; switch (it.DiffType) { case DiffType.delete: requestMethod = "删除"; break; case DiffType.insert: requestMethod = "新增"; break; case DiffType.update: requestMethod = "修改"; break; } // 获取请求上下文中的信息(需要在请求中传递) var httpContextAccessor = App.HttpContext; var context = httpContextAccessor.Request; if (context == null) return; UserAgent userAgent = new UserAgent(App.HttpContext); var apiPath = context.Path; //获取修改前修改后的数据 //记录日志 var sysLog = new SysLogEntity(); sysLog.Creator(); sysLog.UserId = App.User?.FindFirst(ClaimConst.CLAINMUSERID)?.Value ?? ""; sysLog.UserName = App.User?.FindFirst(ClaimConst.CLAINMREALNAME)?.Value ?? ""; sysLog.Type = 3; sysLog.Level = 1; sysLog.IPAddress = NetHelper.Ip; sysLog.RequestURL = apiPath; sysLog.RequestMethod = requestMethod; sysLog.ModuleName = it.BusinessData?.ToString() ?? ""; sysLog.RequestDuration = (int)(db.Ado.SqlExecutionTime.TotalSeconds * 1000); //sysLog.PlatForm = string.Format("{0}-{1}", userAgent.OS.ToString(), userAgent.RawValue); //sysLog.ObjectId = item; //sysLog.Json = $"审核人【{_userManager.RealName}】,审核时间【{DateTime.Now}】,"; //_repository.AsSugarClient().Insertable(sysLog).ExecuteCommand(); sysLog.Json = getDiff(it.BeforeData, it.AfterData).diffData ?? "";//修改的数据 db.Insertable<SysLogEntity>(sysLog).ExecuteCommand();//保存数据,不要添加.EnableDiffLogEvent()方法 }; // 配置实体假删除过滤器 db.QueryFilter.AddTableFilter<ISoftDeleteFilter>(it => SqlFunc.IsNull(it.DeleteMark, 0) == 0); }
热忱回答(5)
-
VIP0
1周前测试出来好像是二十分钟不动页面就会出现
0 回复 -
VIP0
1周前测试出来好像是二十分钟不动页面就会出现
0 回复 -
fate sta VIP0
1周前Pooling=false
字符串加上这个测试一下。
0 回复 -
VIP0
1周前@fate sta:好的,
0 回复 -
VIP0
1周前@fate sta:测试了下没问题了,谢谢老师
0 回复