From d636034f06fd58eb6b35f72b674c8fc6b334ecf3 Mon Sep 17 00:00:00 2001 From: pofi Date: Tue, 28 Mar 2023 15:29:09 +0800 Subject: [PATCH] =?UTF-8?q?=E7=AE=80=E5=8C=96startup?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Extensions/ConfigureEventBusExtensions.cs | 56 +++++++++++ ...sions.cs => ConfigureLoggingExtensions.cs} | 4 +- .../ConfigureMvcControllerExtensions.cs | 77 +++++++++++++++ ...ns.cs => ConfigureOSSServiceExtensions.cs} | 4 +- .../Extensions/ConfigureSqlSugarExtensions.cs | 74 ++++++++++++++ .../Extensions/SqlSugarConfigureExtensions.cs | 69 ------------- apihost/Tnb.API.Entry/Startup.cs | 98 ++----------------- apihost/Tnb.API.Entry/appsettings.json | 8 -- common/Tnb.Common/Tnb.Common.csproj | 2 +- common/Tnb.SqlSugar/Tnb.SqlSugar.csproj | 2 +- 10 files changed, 221 insertions(+), 173 deletions(-) create mode 100644 apihost/Tnb.API.Entry/Extensions/ConfigureEventBusExtensions.cs rename apihost/Tnb.API.Entry/Extensions/{LoggingConfigureExtensions.cs => ConfigureLoggingExtensions.cs} (95%) create mode 100644 apihost/Tnb.API.Entry/Extensions/ConfigureMvcControllerExtensions.cs rename apihost/Tnb.API.Entry/Extensions/{OSSServiceConfigureExtensions.cs => ConfigureOSSServiceExtensions.cs} (92%) create mode 100644 apihost/Tnb.API.Entry/Extensions/ConfigureSqlSugarExtensions.cs delete mode 100644 apihost/Tnb.API.Entry/Extensions/SqlSugarConfigureExtensions.cs diff --git a/apihost/Tnb.API.Entry/Extensions/ConfigureEventBusExtensions.cs b/apihost/Tnb.API.Entry/Extensions/ConfigureEventBusExtensions.cs new file mode 100644 index 00000000..180ede3a --- /dev/null +++ b/apihost/Tnb.API.Entry/Extensions/ConfigureEventBusExtensions.cs @@ -0,0 +1,56 @@ +using JNPF; +using JNPF.Common.Options; +using JNPF.EventHandler; +using OnceMi.AspNetCore.OSS; + +namespace Microsoft.Extensions.DependencyInjection; + +/// +/// OSS服务配置拓展. +/// +public static class ConfigureEventBusExtensions +{ + /// + /// OSS服务配置. + /// + /// + /// + public static IServiceCollection ConfigureEventBus(this IServiceCollection services) + { + // 注册EventBus服务 + services.AddEventBus(options => + { + //// 创建连接工厂 + //var factory = new RabbitMQ.Client.ConnectionFactory + //{ + // // 设置主机名 + // HostName = "192.168.0.232", + + // // 用户名 + // UserName = "jnpf", + + // // 密码 + // Password = "jnpf@2019", + //}; + + //// 创建默认内存通道事件源对象,可自定义队列路由key,比如这里是 eventbus + //var rbmqEventSourceStorer = new RabbitMQEventSourceStorer(factory, "eventbus", 3000); + + //// 替换默认事件总线存储器 + //options.ReplaceStorer(serviceProvider => + //{ + // return rbmqEventSourceStorer; + //}); + + options.UseUtcTimestamp = false; + + // 不启用事件日志 + options.LogEnabled = false; + + // 事件执行器(失败重试) + options.AddExecutor(); + }); + + return services; + } +} \ No newline at end of file diff --git a/apihost/Tnb.API.Entry/Extensions/LoggingConfigureExtensions.cs b/apihost/Tnb.API.Entry/Extensions/ConfigureLoggingExtensions.cs similarity index 95% rename from apihost/Tnb.API.Entry/Extensions/LoggingConfigureExtensions.cs rename to apihost/Tnb.API.Entry/Extensions/ConfigureLoggingExtensions.cs index 02a3bd50..31797ac2 100644 --- a/apihost/Tnb.API.Entry/Extensions/LoggingConfigureExtensions.cs +++ b/apihost/Tnb.API.Entry/Extensions/ConfigureLoggingExtensions.cs @@ -10,11 +10,11 @@ namespace Microsoft.Extensions.DependencyInjection; /// /// SqlSugar配置拓展. /// -public static class LoggingConfigureExtensions +public static class ConfigureLoggingExtensions { const string DATEFORMAT = "HH:mm:ss.fff"; - public static IServiceCollection LoggingConfigure(this IServiceCollection services) + public static IServiceCollection ConfigureLogging(this IServiceCollection services) { services.AddConsoleFormatter(option => { diff --git a/apihost/Tnb.API.Entry/Extensions/ConfigureMvcControllerExtensions.cs b/apihost/Tnb.API.Entry/Extensions/ConfigureMvcControllerExtensions.cs new file mode 100644 index 00000000..4dc1208b --- /dev/null +++ b/apihost/Tnb.API.Entry/Extensions/ConfigureMvcControllerExtensions.cs @@ -0,0 +1,77 @@ +using JNPF; +using JNPF.Common.Core.Filter; +using JNPF.Common.Options; +using JNPF.EventHandler; +using JNPF.JsonSerialization; +using JNPF.UnifyResult; +using Microsoft.AspNetCore.HttpOverrides; +using Newtonsoft.Json.Serialization; +using Newtonsoft.Json; +using OnceMi.AspNetCore.OSS; +using JNPF.API.Entry.Handlers; +using JNPF.Common.Cache; + +namespace Microsoft.Extensions.DependencyInjection; + +/// +/// OSS服务配置拓展. +/// +public static class ConfigureMvcControllerExtensions +{ + /// + /// OSS服务配置. + /// + /// + /// + public static IServiceCollection ConfigureMvcController(this IServiceCollection services) + { + services.AddControllers() + .AddMvcFilter() + .AddInjectWithUnifyResult() + .AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null) + .AddNewtonsoftJson(options => + { + // 默认命名规则 + options.SerializerSettings.ContractResolver = new DefaultContractResolver(); + + // 设置时区为 UTC + options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc; + + // 格式化json输出的日期格式 + options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; + + // 忽略空值 + // options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; + + // 忽略循环引用 + options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; + + // 格式化json输出的日期格式为时间戳 + options.SerializerSettings.Converters.Add(new NewtonsoftDateTimeJsonConverter()); + }); + + // 配置Nginx转发获取客户端真实IP + // 注1:如果负载均衡不是在本机通过 Loopback 地址转发请求的,一定要加上options.KnownNetworks.Clear()和options.KnownProxies.Clear() + // 注2:如果设置环境变量 ASPNETCORE_FORWARDEDHEADERS_ENABLED 为 True,则不需要下面的配置代码 + services.Configure(options => + { + options.ForwardedHeaders = ForwardedHeaders.All; + options.KnownNetworks.Clear(); + options.KnownProxies.Clear(); + }); + + // Jwt处理程序 + services.AddJwt(enableGlobalAuthorize: true); + + // 跨域 + services.AddCorsAccessor(); + + services.AddConfigurableOptions(); + services.AddSession(); + services.AddMemoryCache(); // 使用本地缓存必须添加 + + services.AddSingleton(); + + return services; + } +} \ No newline at end of file diff --git a/apihost/Tnb.API.Entry/Extensions/OSSServiceConfigureExtensions.cs b/apihost/Tnb.API.Entry/Extensions/ConfigureOSSServiceExtensions.cs similarity index 92% rename from apihost/Tnb.API.Entry/Extensions/OSSServiceConfigureExtensions.cs rename to apihost/Tnb.API.Entry/Extensions/ConfigureOSSServiceExtensions.cs index 9a422700..348a87d7 100644 --- a/apihost/Tnb.API.Entry/Extensions/OSSServiceConfigureExtensions.cs +++ b/apihost/Tnb.API.Entry/Extensions/ConfigureOSSServiceExtensions.cs @@ -7,14 +7,14 @@ namespace Microsoft.Extensions.DependencyInjection; /// /// OSS服务配置拓展. /// -public static class OSSServiceConfigureExtensions +public static class ConfigureOSSServiceExtensions { /// /// OSS服务配置. /// /// /// - public static IServiceCollection OSSServiceConfigure(this IServiceCollection services) + public static IServiceCollection ConfigureOSSService(this IServiceCollection services) { // 获取选项 OssOptions oss = App.GetConfig("OSS", true); diff --git a/apihost/Tnb.API.Entry/Extensions/ConfigureSqlSugarExtensions.cs b/apihost/Tnb.API.Entry/Extensions/ConfigureSqlSugarExtensions.cs new file mode 100644 index 00000000..31dc6bbd --- /dev/null +++ b/apihost/Tnb.API.Entry/Extensions/ConfigureSqlSugarExtensions.cs @@ -0,0 +1,74 @@ +using System.ComponentModel.DataAnnotations; +using System.Reflection; +using JNPF; +using JNPF.DatabaseAccessor; +using JNPF.Logging; +using Spire.Xls; +using SqlSugar; + +namespace Microsoft.Extensions.DependencyInjection; + +/// +/// SqlSugar配置拓展. +/// +public static class ConfigureSqlSugarExtensions +{ + public static IServiceCollection ConfigureSqlSugar(this IServiceCollection services) + { + // 获取选项 + ConnectionStringsOptions conn = App.GetConfig("ConnectionStrings", true); + + List connectConfigList = new List(); + var DBType = (DbType)Enum.Parse(typeof(DbType), conn.DBType); + // 默认数据库 + connectConfigList.Add(new ConnectionConfig + { + ConnectionString = string.Format(conn.DefaultConnection, conn.Host, conn.Port, conn.DBName, conn.UserName, conn.Password), + DbType = DBType, + IsAutoCloseConnection = true, + ConfigId = conn.ConfigId, + InitKeyType = InitKeyType.Attribute, + MoreSettings = new ConnMoreSettings() + { + IsAutoRemoveDataCache = true // 自动清理缓存 + }, + }); + + services.AddSqlSugar(connectConfigList, client => + { + //connectConfigList.ForEach(config => + //{ + // var db = ((SqlSugarScope)client).GetConnectionScope((string)config.ConfigId); + + // // 设置超时时间 + // db.Ado.CommandTimeOut = 30; + + // // 打印SQL语句 + // db.Aop.OnLogExecuting = (sql, pars) => + // { + // var oldColor = Console.ForegroundColor; + // Console.ForegroundColor = ConsoleColor.Green; + // var finalSql = UtilMethods.GetSqlString(db.CurrentConnectionConfig.DbType, sql, pars); + // Console.WriteLine($"【{DateTime.Now.ToString("HH:mm:ss.fff")}——SQL执行完成】{db.Ado.SqlExecutionTime.TotalMilliseconds} ms"); + // Console.WriteLine(finalSql); + // Console.ForegroundColor = oldColor; + // if (db.Ado.SqlExecutionTime.TotalMilliseconds > 3000) + // { + // Log.Warning($"慢查询: {db.Ado.SqlExecutionTime.TotalMilliseconds}ms, SQL: " + finalSql); + // } + // Console.WriteLine(); + // }; + // db.Aop.OnError = (ex) => + // { + // Log.Error(UtilMethods.GetSqlString(db.CurrentConnectionConfig.DbType, ex.Sql, (SugarParameter[])ex.Parametres)); + // }; + //}); + }); + services.AddConfigurableOptions(); + services.AddConfigurableOptions(); + services.AddUnitOfWork(); + + + return services; + } +} \ No newline at end of file diff --git a/apihost/Tnb.API.Entry/Extensions/SqlSugarConfigureExtensions.cs b/apihost/Tnb.API.Entry/Extensions/SqlSugarConfigureExtensions.cs deleted file mode 100644 index 37341330..00000000 --- a/apihost/Tnb.API.Entry/Extensions/SqlSugarConfigureExtensions.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System.ComponentModel.DataAnnotations; -using System.Reflection; -using JNPF; -using JNPF.Logging; -using Spire.Xls; -using SqlSugar; - -namespace Microsoft.Extensions.DependencyInjection; - -/// -/// SqlSugar配置拓展. -/// -public static class SqlSugarConfigureExtensions -{ - public static IServiceCollection SqlSugarConfigure(this IServiceCollection services) - { - // 获取选项 - ConnectionStringsOptions conn = App.GetConfig("ConnectionStrings", true); - - List connectConfigList = new List(); - var DBType = (DbType)Enum.Parse(typeof(DbType), conn.DBType); - // 默认数据库 - connectConfigList.Add(new ConnectionConfig - { - ConnectionString = string.Format(conn.DefaultConnection, conn.Host, conn.Port, conn.DBName, conn.UserName, conn.Password), - DbType = DBType, - IsAutoCloseConnection = true, - ConfigId = conn.ConfigId, - InitKeyType = InitKeyType.Attribute, - MoreSettings = new ConnMoreSettings() - { - IsAutoRemoveDataCache = true // 自动清理缓存 - }, - }); - - services.AddSqlSugar(connectConfigList, client => - { - //connectConfigList.ForEach(config => - //{ - // var db = ((SqlSugarScope)client).GetConnectionScope((string)config.ConfigId); - - // // 设置超时时间 - // db.Ado.CommandTimeOut = 30; - - // // 打印SQL语句 - // db.Aop.OnLogExecuting = (sql, pars) => - // { - // var oldColor = Console.ForegroundColor; - // Console.ForegroundColor = ConsoleColor.Green; - // var finalSql = UtilMethods.GetSqlString(db.CurrentConnectionConfig.DbType, sql, pars); - // Console.WriteLine($"【{DateTime.Now.ToString("HH:mm:ss.fff")}——SQL执行完成】{db.Ado.SqlExecutionTime.TotalMilliseconds} ms"); - // Console.WriteLine(finalSql); - // Console.ForegroundColor = oldColor; - // if (db.Ado.SqlExecutionTime.TotalMilliseconds > 3000) - // { - // Log.Warning($"慢查询: {db.Ado.SqlExecutionTime.TotalMilliseconds}ms, SQL: " + finalSql); - // } - // Console.WriteLine(); - // }; - // db.Aop.OnError = (ex) => - // { - // Log.Error(UtilMethods.GetSqlString(db.CurrentConnectionConfig.DbType, ex.Sql, (SugarParameter[])ex.Parametres)); - // }; - //}); - }); - - return services; - } -} \ No newline at end of file diff --git a/apihost/Tnb.API.Entry/Startup.cs b/apihost/Tnb.API.Entry/Startup.cs index 58552448..e73e43ed 100644 --- a/apihost/Tnb.API.Entry/Startup.cs +++ b/apihost/Tnb.API.Entry/Startup.cs @@ -28,92 +28,19 @@ public class Startup : AppStartup { public void ConfigureServices(IServiceCollection services) { + services.ConfigureMvcController(); + // SqlSugar - services.SqlSugarConfigure(); - - // Jwt处理程序 - services.AddJwt(enableGlobalAuthorize: true); - - // 跨域 - services.AddCorsAccessor(); + //services.SqlSugarConfigure(); + services.ConfigureSqlSugar(); // 注册EventBus服务 - services.AddEventBus(options => - { - //// 创建连接工厂 - //var factory = new RabbitMQ.Client.ConnectionFactory - //{ - // // 设置主机名 - // HostName = "192.168.0.232", - - // // 用户名 - // UserName = "jnpf", - - // // 密码 - // Password = "jnpf@2019", - //}; - - //// 创建默认内存通道事件源对象,可自定义队列路由key,比如这里是 eventbus - //var rbmqEventSourceStorer = new RabbitMQEventSourceStorer(factory, "eventbus", 3000); - - //// 替换默认事件总线存储器 - //options.ReplaceStorer(serviceProvider => - //{ - // return rbmqEventSourceStorer; - //}); - - options.UseUtcTimestamp = false; - - // 不启用事件日志 - options.LogEnabled = false; - - // 事件执行器(失败重试) - options.AddExecutor(); - }); + services.ConfigureEventBus(); // 注册远程请求 services.AddRemoteRequest(); - services.AddConfigurableOptions(); - services.AddConfigurableOptions(); - services.AddConfigurableOptions(); - - services.AddControllers() - .AddMvcFilter() - .AddInjectWithUnifyResult() - .AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null) - .AddNewtonsoftJson(options => - { - // 默认命名规则 - options.SerializerSettings.ContractResolver = new DefaultContractResolver(); - - // 设置时区为 UTC - options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc; - - // 格式化json输出的日期格式 - options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; - - // 忽略空值 - // options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; - - // 忽略循环引用 - options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; - - // 格式化json输出的日期格式为时间戳 - options.SerializerSettings.Converters.Add(new NewtonsoftDateTimeJsonConverter()); - }); - - // 配置Nginx转发获取客户端真实IP - // 注1:如果负载均衡不是在本机通过 Loopback 地址转发请求的,一定要加上options.KnownNetworks.Clear()和options.KnownProxies.Clear() - // 注2:如果设置环境变量 ASPNETCORE_FORWARDEDHEADERS_ENABLED 为 True,则不需要下面的配置代码 - services.Configure(options => - { - options.ForwardedHeaders = ForwardedHeaders.All; - options.KnownNetworks.Clear(); - options.KnownProxies.Clear(); - }); - - // 视图引擎 + // 视图引擎 services.AddViewEngine(); // 任务调度 @@ -128,16 +55,9 @@ public class Startup : AppStartup // 微信 services.AddSenparcGlobalServices(App.Configuration) // Senparc.CO2NET 全局注册 .AddSenparcWeixinServices(App.Configuration); // Senparc.Weixin 注册(如果使用Senparc.Weixin SDK则添加) - services.AddSession(); - services.AddMemoryCache(); // 使用本地缓存必须添加 - services.LoggingConfigure(); - - services.AddUnitOfWork(); - - services.OSSServiceConfigure(); - - services.AddSingleton(); + services.ConfigureLogging(); + services.ConfigureOSSService(); services.AddSchedule(); @@ -153,10 +73,8 @@ public class Startup : AppStartup app.UseStaticFiles(); #region 微信 - IRegisterService register = RegisterService.Start(senparcSetting.Value).UseSenparcGlobal();//启动 CO2NET 全局注册,必须! register.UseSenparcWeixin(senparcWeixinSetting.Value, senparcSetting.Value);//微信全局注册,必须! - #endregion app.UseWebSockets(); diff --git a/apihost/Tnb.API.Entry/appsettings.json b/apihost/Tnb.API.Entry/appsettings.json index 819ca1b3..44864973 100644 --- a/apihost/Tnb.API.Entry/appsettings.json +++ b/apihost/Tnb.API.Entry/appsettings.json @@ -1,12 +1,4 @@ { "AllowedHosts": "*", - // 配置扫描目录 - "Kestrel": { - "Endpoints": { - "Http": { - "Url": "http://localhost:5000" - } - } - }, "ConfigurationScanDirectories": [ "Configurations" ] } \ No newline at end of file diff --git a/common/Tnb.Common/Tnb.Common.csproj b/common/Tnb.Common/Tnb.Common.csproj index 7ee24bc2..4d8a9838 100644 --- a/common/Tnb.Common/Tnb.Common.csproj +++ b/common/Tnb.Common/Tnb.Common.csproj @@ -14,9 +14,9 @@ + - diff --git a/common/Tnb.SqlSugar/Tnb.SqlSugar.csproj b/common/Tnb.SqlSugar/Tnb.SqlSugar.csproj index 0995ef7c..4c355b20 100644 --- a/common/Tnb.SqlSugar/Tnb.SqlSugar.csproj +++ b/common/Tnb.SqlSugar/Tnb.SqlSugar.csproj @@ -19,7 +19,7 @@ - +