From 5d5452b53139c4827c9a9f4c6e0c9ba6a9bef3a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=A9=99=E5=AD=90?= <454313500@qq.com> Date: Tue, 26 Oct 2021 15:09:07 +0800 Subject: [PATCH] =?UTF-8?q?=E9=85=8D=E7=BD=AE=E6=96=87=E4=BB=B6=E5=BC=80?= =?UTF-8?q?=E5=85=B3=EF=BC=8C=E6=95=B0=E6=8D=AE=E5=BA=93=E8=AF=BB=E5=86=99?= =?UTF-8?q?=E5=88=86=E7=A6=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/MenuController.cs | 3 +- .../Yi.Framework.ApiMicroservice/Program.cs | 4 +- .../Yi.Framework.ApiMicroservice/Startup.cs | 22 ++-- .../appsettings.json | 29 +++-- .../Yi.Framework.Common/Const/DbConst.cs | 16 +++ .../IOCOptions/MySqlConnOptions.cs | 6 +- .../IOCOptions/SqliteOptions.cs | 3 +- .../Models/Enum/WriteAndReadEnum.cs | 12 +++ .../Yi.Framework.Model/DataContext.cs | 62 ++++++----- .../Yi.Framework.Model/DbInit/DataSeed.cs | 4 +- .../ModelFactory/DbContextExtend.cs | 23 ++++ .../ModelFactory/DbContextFactory.cs | 100 ++++++++++++++++++ .../ModelFactory/IDbContextFactory.cs | 13 +++ .../Yi.Framework.Service/BaseService.cs | 10 +- .../Yi.Framework.Service/T4Service.cs | 9 +- .../Yi.Framework.Service/T4Service.tt | 3 +- .../Yi.Framework.Service/UserService.cs | 3 +- .../Yi.Framework.WebCore/Appsettings.cs | 21 +++- .../BuilderExtend/ApolloExtension.cs | 19 ++-- .../MiddlewareExtend/ConsulRegiterExtend.cs | 49 +++++---- .../MiddlewareExtend/CorsExtension.cs | 25 +++-- .../MiddlewareExtend/DbExtend.cs | 23 ++++ .../MiddlewareExtend/DbSeedInitExtend.cs | 23 ++-- .../MiddlewareExtend/HealthCheckExtension.cs | 15 ++- .../MiddlewareExtend/IocExtension.cs | 6 +- .../MiddlewareExtend/MysqlExtension.cs | 20 ---- .../MiddlewareExtend/RabbitMQExtension.cs | 6 +- .../MiddlewareExtend/RedisExtension.cs | 5 +- .../MiddlewareExtend/SqliteExtension.cs | 20 ---- .../Utility/CustomAutofacModule.cs | 6 +- 30 files changed, 397 insertions(+), 163 deletions(-) create mode 100644 Yi.Framework/Yi.Framework.Common/Const/DbConst.cs create mode 100644 Yi.Framework/Yi.Framework.Common/Models/Enum/WriteAndReadEnum.cs create mode 100644 Yi.Framework/Yi.Framework.Model/ModelFactory/DbContextExtend.cs create mode 100644 Yi.Framework/Yi.Framework.Model/ModelFactory/DbContextFactory.cs create mode 100644 Yi.Framework/Yi.Framework.Model/ModelFactory/IDbContextFactory.cs create mode 100644 Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/DbExtend.cs delete mode 100644 Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/MysqlExtension.cs delete mode 100644 Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/SqliteExtension.cs diff --git a/Yi.Framework/Yi.Framework.ApiMicroservice/Controllers/MenuController.cs b/Yi.Framework/Yi.Framework.ApiMicroservice/Controllers/MenuController.cs index bbacced2..8d464936 100644 --- a/Yi.Framework/Yi.Framework.ApiMicroservice/Controllers/MenuController.cs +++ b/Yi.Framework/Yi.Framework.ApiMicroservice/Controllers/MenuController.cs @@ -1,4 +1,5 @@ -using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; diff --git a/Yi.Framework/Yi.Framework.ApiMicroservice/Program.cs b/Yi.Framework/Yi.Framework.ApiMicroservice/Program.cs index cbe8c6a4..646320e7 100644 --- a/Yi.Framework/Yi.Framework.ApiMicroservice/Program.cs +++ b/Yi.Framework/Yi.Framework.ApiMicroservice/Program.cs @@ -28,7 +28,7 @@ namespace Yi.Framework.ApiMicroservice #region //Apollo #endregion - //configurationBuilder.AddApolloService("Yi"); + configurationBuilder.AddApolloService("Yi"); }) .ConfigureLogging(loggingBuilder => { @@ -38,7 +38,7 @@ namespace Yi.Framework.ApiMicroservice }) .ConfigureWebHostDefaults(webBuilder => { - webBuilder.UseStartup().UseUrls("https://*:44329"); + webBuilder.UseStartup(); }).UseServiceProviderFactory(new AutofacServiceProviderFactory()); } } diff --git a/Yi.Framework/Yi.Framework.ApiMicroservice/Startup.cs b/Yi.Framework/Yi.Framework.ApiMicroservice/Startup.cs index bb5a833f..2283df4d 100644 --- a/Yi.Framework/Yi.Framework.ApiMicroservice/Startup.cs +++ b/Yi.Framework/Yi.Framework.ApiMicroservice/Startup.cs @@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Yi.Framework.Model.ModelFactory; using Yi.Framework.WebCore.MiddlewareExtend; using Yi.Framework.WebCore.Utility; @@ -49,24 +50,19 @@ namespace Yi.Framework.ApiMicroservice services.AddJwtService(); #region - //Sqlite + //ݿ #endregion - services.AddSqliteService(); - - #region - //MySql - #endregion - services.AddMysqlService(); + services.AddDbService(); #region //Redis #endregion - //services.AddRedisService(); + services.AddRedisService(); #region //RabbitMQ #endregion - //services.AddRabbitMQService(); + services.AddRabbitMQService(); } @@ -82,7 +78,7 @@ namespace Yi.Framework.ApiMicroservice #endregion // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env,DbContext _Db) + public void Configure(IApplicationBuilder app, IWebHostEnvironment env,IDbContextFactory _DbFactory) { //if (env.IsDevelopment()) { @@ -119,7 +115,7 @@ namespace Yi.Framework.ApiMicroservice #region //ע #endregion - //app.UseHealthCheckMiddleware(); + app.UseHealthCheckMiddleware(); #region //Ȩע @@ -134,12 +130,12 @@ namespace Yi.Framework.ApiMicroservice #region //Consulע #endregion - //app.UseConsulService(); + app.UseConsulService(); #region //ݿע #endregion - app.UseDbSeedInitService(_Db); + app.UseDbSeedInitService(_DbFactory); #region //Endpointsע diff --git a/Yi.Framework/Yi.Framework.ApiMicroservice/appsettings.json b/Yi.Framework/Yi.Framework.ApiMicroservice/appsettings.json index abc37e3f..6416d435 100644 --- a/Yi.Framework/Yi.Framework.ApiMicroservice/appsettings.json +++ b/Yi.Framework/Yi.Framework.ApiMicroservice/appsettings.json @@ -1,4 +1,5 @@ { + "urls": "http://*:19000", "Logging": { "LogLevel": { "Default": "Information", @@ -7,19 +8,33 @@ } }, "AllowedHosts": "*", + + "Consul_Enabled": false, + "DbSeed_Enabled": true, + "Apollo_Enabled": false, + "HealthCheck_Enabled": false, + "Cors_Enabled": true, + "RabbitMQ_Enabled": false, + "Redis_Enabled": false, + "Kafka_Enabled": false, + "MutiDB_Enabled": true, + "DbList": [ "Sqlite", "Mysql", "Sqlserver","Oracle"], + "DbSelect": "Mysql", + + "DbConn": { + "WriteUrl": "server=118.195.191.41;port=3306;database=YIDB;user id=root;password=Qz52013142020.", + "ReadUrl": [ + "server=118.195.191.41;port=3306;database=YIDB;user id=root;password=Qz52013142020.", + "server=118.195.191.41;port=3306;database=YIDB;user id=root;password=Qz52013142020.", + "server=118.195.191.41;port=3306;database=YIDB;user id=root;password=Qz52013142020." + ] + }, "Apollo": { "AppId": "Yi.Framework.ApiMicroservice", "Env": "DEV", "MetaServer": "http://192.168.2.168:8080", "ConfigServer": [ "http://192.168.2.168:8080" ] }, - "SqliteConn": { - "Url": "Filename=YIDB.db" - }, - "MysqlConn": { - "Url": "server=118.195.191.41;port=3306;database=YIDB;user id=root;password=Qz52013142020." - }, - "JWTTokenOptions": { "Audience": "http://localhost:7000", "Issuer": "http://localhost:7000", diff --git a/Yi.Framework/Yi.Framework.Common/Const/DbConst.cs b/Yi.Framework/Yi.Framework.Common/Const/DbConst.cs new file mode 100644 index 00000000..99950713 --- /dev/null +++ b/Yi.Framework/Yi.Framework.Common/Const/DbConst.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Yi.Framework.Common.Const +{ + public class DbConst + { + public const string Mysql = "Mysql"; + public const string Sqlite = "Sqlite"; + public const string Sqlserver = "Sqlserver"; + public const string Oracle = "Oracle"; + } +} diff --git a/Yi.Framework/Yi.Framework.Common/IOCOptions/MySqlConnOptions.cs b/Yi.Framework/Yi.Framework.Common/IOCOptions/MySqlConnOptions.cs index f6a981f0..c5ae46b1 100644 --- a/Yi.Framework/Yi.Framework.Common/IOCOptions/MySqlConnOptions.cs +++ b/Yi.Framework/Yi.Framework.Common/IOCOptions/MySqlConnOptions.cs @@ -1,9 +1,11 @@ using System; +using System.Collections.Generic; namespace Yi.Framework.Common.IOCOptions { - public class MySqlConnOptions + public class DbConnOptions { - public string Url { get; set; } + public string WriteUrl { get; set; } + public List ReadUrl { get; set; } } } diff --git a/Yi.Framework/Yi.Framework.Common/IOCOptions/SqliteOptions.cs b/Yi.Framework/Yi.Framework.Common/IOCOptions/SqliteOptions.cs index 0ac7b25d..bd2caf1e 100644 --- a/Yi.Framework/Yi.Framework.Common/IOCOptions/SqliteOptions.cs +++ b/Yi.Framework/Yi.Framework.Common/IOCOptions/SqliteOptions.cs @@ -8,6 +8,7 @@ namespace Yi.Framework.Common.IOCOptions { public class SqliteOptions { - public string Url { get; set; } + public string WriteUrl { get; set; } + public List ReadUrl { get; set; } } } diff --git a/Yi.Framework/Yi.Framework.Common/Models/Enum/WriteAndReadEnum.cs b/Yi.Framework/Yi.Framework.Common/Models/Enum/WriteAndReadEnum.cs new file mode 100644 index 00000000..c67de196 --- /dev/null +++ b/Yi.Framework/Yi.Framework.Common/Models/Enum/WriteAndReadEnum.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Yi.Framework.Common.Enum +{ + public enum WriteAndReadEnum + { + Write, //主库操作 + Read //从库操作 + } +} diff --git a/Yi.Framework/Yi.Framework.Model/DataContext.cs b/Yi.Framework/Yi.Framework.Model/DataContext.cs index 0399156d..c5285d45 100644 --- a/Yi.Framework/Yi.Framework.Model/DataContext.cs +++ b/Yi.Framework/Yi.Framework.Model/DataContext.cs @@ -5,37 +5,49 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using Yi.Framework.Common.Const; using Yi.Framework.Common.IOCOptions; using Yi.Framework.Model.Models; namespace Yi.Framework.Model { - //Add-Migration yi-1 - //Update-Database yi-1 - public partial class DataContext : DbContext + //Add-Migration yi-1 + //Update-Database yi-1 + public partial class DataContext : DbContext { - private readonly IOptionsMonitor _optionsMonitor; - private readonly string _connStr; + //private readonly IOptionsMonitor _optionsMonitor; + private string _connStr; + public static string DbSelect = DbConst.Mysql; + //public DataContext(IOptionsMonitor optionsMonitor) + //{ + // _optionsMonitor = optionsMonitor; + // _connStr = _optionsMonitor.CurrentValue.WriteUrl; + //} + public DbContext ToWriteOrRead(string connstr) + { + _connStr = connstr; + return this; + } + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + if (!optionsBuilder.IsConfigured) + { + switch (DbSelect) + { + case DbConst.Mysql: + var serverVersion = new MySqlServerVersion(new Version(8, 0, 21)); + optionsBuilder.UseMySql(_connStr, serverVersion); break; + case DbConst.Sqlite: + optionsBuilder.UseSqlite(_connStr); break; + case DbConst.Sqlserver: + optionsBuilder.UseSqlServer(_connStr);break; + case DbConst.Oracle: + optionsBuilder.UseOracle(_connStr);break; + default: + Console.WriteLine("错误!请确保你选择了正确的数据库!");break; + } + } + } - public DataContext(IOptionsMonitor optionsMonitor) - { - _optionsMonitor = optionsMonitor; - _connStr = _optionsMonitor.CurrentValue.Url; - } - - public DataContext(string connstr) - { - _connStr = connstr; - } - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - if (!optionsBuilder.IsConfigured) - { - //optionsBuilder.UseSqlite(_connStr); - var serverVersion = new MySqlServerVersion(new Version(8, 0, 21)); - optionsBuilder.UseMySql(_connStr, serverVersion); - } - } - } } diff --git a/Yi.Framework/Yi.Framework.Model/DbInit/DataSeed.cs b/Yi.Framework/Yi.Framework.Model/DbInit/DataSeed.cs index 80fa1f08..76f79513 100644 --- a/Yi.Framework/Yi.Framework.Model/DbInit/DataSeed.cs +++ b/Yi.Framework/Yi.Framework.Model/DbInit/DataSeed.cs @@ -4,14 +4,16 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using Yi.Framework.Model.ModelFactory; using Yi.Framework.Model.Models; namespace Yi.Framework.Model.DbInit { public class DataSeed { - public async static Task SeedAsync(DbContext _Db) + public async static Task SeedAsync(IDbContextFactory _DbFactory) { + var _Db= _DbFactory.ConnWriteOrRead(Common.Enum.WriteAndReadEnum.Write); if (!_Db.Set().Any()) { await _Db.Set().AddAsync(new user diff --git a/Yi.Framework/Yi.Framework.Model/ModelFactory/DbContextExtend.cs b/Yi.Framework/Yi.Framework.Model/ModelFactory/DbContextExtend.cs new file mode 100644 index 00000000..d4cb3846 --- /dev/null +++ b/Yi.Framework/Yi.Framework.Model/ModelFactory/DbContextExtend.cs @@ -0,0 +1,23 @@ +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Text; + +namespace Yi.Framework.Model.ModelFactory +{ + public static class DbContextExtend + { + public static DbContext ToWriteOrRead(this DbContext dbContext, string conn) + { + if (dbContext is DataContext) + { + + var context= (DataContext)dbContext; // context 是 EFCoreContext 实例; + + return context.ToWriteOrRead(conn); + } + else + throw new Exception(); + } + } +} diff --git a/Yi.Framework/Yi.Framework.Model/ModelFactory/DbContextFactory.cs b/Yi.Framework/Yi.Framework.Model/ModelFactory/DbContextFactory.cs new file mode 100644 index 00000000..a156afdf --- /dev/null +++ b/Yi.Framework/Yi.Framework.Model/ModelFactory/DbContextFactory.cs @@ -0,0 +1,100 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; +using System; +using System.Collections.Generic; +using System.Text; +using Yi.Framework.Common.Enum; +using Yi.Framework.Common.IOCOptions; + +namespace Yi.Framework.Model.ModelFactory +{ + public class DbContextFactory : IDbContextFactory + { + + private DbContext _Context = null; + + private DbConnOptions _readAndWrite = null; + + public static bool MutiDB_Enabled = false; + //private static int _iSeed = 0;//应该long + + /// + ///能把链接信息也注入进来 + ///需要IOptionsMonitor + /// + /// + public DbContextFactory(DbContext context, IOptionsMonitor options) + { + _readAndWrite = options.CurrentValue; + this._Context = context; + } + public DbContext ConnWriteOrRead(WriteAndReadEnum writeAndRead) + { + //判断枚举,不同的枚举可以创建不同的Context 或者更换Context链接; + if (MutiDB_Enabled) + { + switch (writeAndRead) + { + case WriteAndReadEnum.Write: + ToWrite(); + break; //选择链接//更换_Context链接 //选择链接 + case WriteAndReadEnum.Read: + ToRead(); + break; //选择链接//更换_Context链接 + default: + break; + } + } + else + { + ToWrite(); + } + + return _Context; + } + + /// + /// 更换成主库连接 + /// + /// + private void ToWrite() + { + string conn = _readAndWrite.WriteUrl; + //_Context.Database.GetDbConnection().; + _Context.ToWriteOrRead(conn); + } + + + private static int _iSeed = 0; + + /// + /// 更换成主库连接 + /// + /// ///策略---数据库查询的负载均衡 + /// + /// + private void ToRead() + { + string conn = string.Empty; + { + // //随机 + //int Count= _readAndWrite.ReadConnectionList.Count; + //int index= new Random().Next(0, Count); + //conn = _readAndWrite.ReadConnectionList[index]; + } + { + //来一个轮询 + conn = this._readAndWrite.ReadUrl[_iSeed++ % this._readAndWrite.ReadUrl.Count];//轮询; + } + { + ///是不是可以直接配置到配置文件里面 + } + _Context.ToWriteOrRead(conn); + } + + //public DbContext CreateContext() + //{ + + //} + } +} diff --git a/Yi.Framework/Yi.Framework.Model/ModelFactory/IDbContextFactory.cs b/Yi.Framework/Yi.Framework.Model/ModelFactory/IDbContextFactory.cs new file mode 100644 index 00000000..818bca67 --- /dev/null +++ b/Yi.Framework/Yi.Framework.Model/ModelFactory/IDbContextFactory.cs @@ -0,0 +1,13 @@ +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Text; +using Yi.Framework.Common.Enum; + +namespace Yi.Framework.Model.ModelFactory +{ + public interface IDbContextFactory + { + public DbContext ConnWriteOrRead(WriteAndReadEnum writeAndRead); + } +} diff --git a/Yi.Framework/Yi.Framework.Service/BaseService.cs b/Yi.Framework/Yi.Framework.Service/BaseService.cs index e03db0f0..7cb12069 100644 --- a/Yi.Framework/Yi.Framework.Service/BaseService.cs +++ b/Yi.Framework/Yi.Framework.Service/BaseService.cs @@ -5,16 +5,22 @@ using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; +using Yi.Framework.Common.Enum; using Yi.Framework.Interface; +using Yi.Framework.Model.ModelFactory; namespace Yi.Framework.Service { public class BaseService : IBaseService where T : class, new() { public DbContext _Db; - public BaseService(DbContext Db) + public DbContext _Db2; + public IDbContextFactory _DbFactory; + public BaseService(IDbContextFactory DbFactory) { - _Db = Db; + _DbFactory = DbFactory; + _Db = DbFactory.ConnWriteOrRead(WriteAndReadEnum.Write); + _Db2 = DbFactory.ConnWriteOrRead(WriteAndReadEnum.Read); } public async Task GetEntityById(int id) diff --git a/Yi.Framework/Yi.Framework.Service/T4Service.cs b/Yi.Framework/Yi.Framework.Service/T4Service.cs index ba836d59..e0e80aa5 100644 --- a/Yi.Framework/Yi.Framework.Service/T4Service.cs +++ b/Yi.Framework/Yi.Framework.Service/T4Service.cs @@ -6,13 +6,14 @@ using System.Threading.Tasks; using Yi.Framework.Model.Models; using Yi.Framework.Interface; using Microsoft.EntityFrameworkCore; +using Yi.Framework.Model.ModelFactory; namespace Yi.Framework.Service { public partial class MenuService:BaseService,IMenuService { - public MenuService(DbContext Db):base(Db){ } + public MenuService(IDbContextFactory DbFactory):base(DbFactory){ } public async Task DelListByUpdateAsync(List _ids) { @@ -30,7 +31,7 @@ namespace Yi.Framework.Service public partial class MouldService:BaseService,IMouldService { - public MouldService(DbContext Db):base(Db){ } + public MouldService(IDbContextFactory DbFactory):base(DbFactory){ } public async Task DelListByUpdateAsync(List _ids) { @@ -48,7 +49,7 @@ namespace Yi.Framework.Service public partial class RoleService:BaseService,IRoleService { - public RoleService(DbContext Db):base(Db){ } + public RoleService(IDbContextFactory DbFactory):base(DbFactory){ } public async Task DelListByUpdateAsync(List _ids) { @@ -66,7 +67,7 @@ namespace Yi.Framework.Service public partial class UserService:BaseService,IUserService { - public UserService(DbContext Db):base(Db){ } + public UserService(IDbContextFactory DbFactory):base(DbFactory){ } public async Task DelListByUpdateAsync(List _ids) { diff --git a/Yi.Framework/Yi.Framework.Service/T4Service.tt b/Yi.Framework/Yi.Framework.Service/T4Service.tt index 6353b6f7..ba340807 100644 --- a/Yi.Framework/Yi.Framework.Service/T4Service.tt +++ b/Yi.Framework/Yi.Framework.Service/T4Service.tt @@ -29,6 +29,7 @@ using System.Threading.Tasks; using Yi.Framework.Model.Models; using Yi.Framework.Interface; using Microsoft.EntityFrameworkCore; +using Yi.Framework.Model.ModelFactory; namespace Yi.Framework.Service { @@ -38,7 +39,7 @@ namespace Yi.Framework.Service public partial class <#= fn #>Service:BaseService<<#= k #>>,I<#= fn #>Service { - public <#= fn #>Service(DbContext Db):base(Db){ } + public <#= fn #>Service(IDbContextFactory DbFactory):base(DbFactory){ } public async Task DelListByUpdateAsync(List _ids) { diff --git a/Yi.Framework/Yi.Framework.Service/UserService.cs b/Yi.Framework/Yi.Framework.Service/UserService.cs index dc919a14..d6975c47 100644 --- a/Yi.Framework/Yi.Framework.Service/UserService.cs +++ b/Yi.Framework/Yi.Framework.Service/UserService.cs @@ -7,6 +7,7 @@ using System.Text; using System.Threading.Tasks; using Yi.Framework.Interface; using Yi.Framework.Model; +using Yi.Framework.Model.ModelFactory; using Yi.Framework.Model.Models; namespace Yi.Framework.Service @@ -14,7 +15,7 @@ namespace Yi.Framework.Service public partial class UserService : BaseService, IUserService { private IRoleService _roleService; - public UserService(DbContext Db, IRoleService roleService) : base(Db) + public UserService(IDbContextFactory DbFactory, IRoleService roleService) : base(DbFactory) { _roleService = roleService; } diff --git a/Yi.Framework/Yi.Framework.WebCore/Appsettings.cs b/Yi.Framework/Yi.Framework.WebCore/Appsettings.cs index 5e07a61c..ae8963cb 100644 --- a/Yi.Framework/Yi.Framework.WebCore/Appsettings.cs +++ b/Yi.Framework/Yi.Framework.WebCore/Appsettings.cs @@ -9,7 +9,7 @@ namespace Yi.Framework.WebCore /// /// appsettings.json操作类 /// - public class Appsettings + public class Appsettings { static IConfiguration Configuration { get; set; } static string contentPath { get; set; } @@ -26,7 +26,7 @@ namespace Yi.Framework.WebCore .Add(new JsonConfigurationSource { Path = Path, Optional = false, ReloadOnChange = true })//这样的话,可以直接读目录里的json文件,而不是 bin 文件夹下的,所以不用修改复制属性 .Build(); } - + public Appsettings(IConfiguration configuration) { Configuration = configuration; @@ -52,6 +52,23 @@ namespace Yi.Framework.WebCore return ""; } + public static bool appBool(params string[] sections) + { + + return Bool(app(sections)); + + } + + public static bool Bool(object thisValue) + { + bool reval = false; + if (thisValue != null && thisValue != DBNull.Value && bool.TryParse(thisValue.ToString(), out reval)) + { + return reval; + } + return reval; + } + /// /// 递归获取配置信息数组 /// diff --git a/Yi.Framework/Yi.Framework.WebCore/BuilderExtend/ApolloExtension.cs b/Yi.Framework/Yi.Framework.WebCore/BuilderExtend/ApolloExtension.cs index 5055c222..0ecec572 100644 --- a/Yi.Framework/Yi.Framework.WebCore/BuilderExtend/ApolloExtension.cs +++ b/Yi.Framework/Yi.Framework.WebCore/BuilderExtend/ApolloExtension.cs @@ -22,18 +22,21 @@ namespace Yi.Framework.WebCore.BuilderExtend //阿波罗的日志级别调整 LogManager.UseConsoleLogging(LogLevel.Warn); var root = builder.Build(); - var apolloBuilder = builder.AddApollo(root.GetSection("apollo")).AddDefault(); - - - foreach (var item in NameSpace) + if (Appsettings.Bool(root["Apollo_Enabled"])) { - apolloBuilder.AddNamespace(item, ConfigFileFormat.Json); - } - //监听apollo配置 - Monitor(builder.Build()); + var apolloBuilder = builder.AddApollo(root.GetSection("apollo")).AddDefault(); + + foreach (var item in NameSpace) + { + apolloBuilder.AddNamespace(item, ConfigFileFormat.Json); + } + //监听apollo配置 + Monitor(builder.Build()); + } + } #region private /// diff --git a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/ConsulRegiterExtend.cs b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/ConsulRegiterExtend.cs index 90d08025..25b2c3e2 100644 --- a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/ConsulRegiterExtend.cs +++ b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/ConsulRegiterExtend.cs @@ -23,36 +23,39 @@ namespace Yi.Framework.WebCore.MiddlewareExtend /// /// /// - public static void UseConsulService(this IApplicationBuilder app) + public static void UseConsulService(this IApplicationBuilder app) { - var consulRegisterOption= Appsettings.app("ConsulRegisterOption"); - var consulClientOption= Appsettings.app("ConsulRegisterOption"); - using (ConsulClient client = new ConsulClient(c => - { - c.Address = new Uri($"http://{consulClientOption.IP}:{consulClientOption.Port}/"); - c.Datacenter = consulClientOption.Datacenter; - })) + if (Appsettings.appBool("Consul_Enabled")) { - client.Agent.ServiceRegister(new AgentServiceRegistration() + var consulRegisterOption = Appsettings.app("ConsulRegisterOption"); + + var consulClientOption = Appsettings.app("ConsulRegisterOption"); + using (ConsulClient client = new ConsulClient(c => + { + c.Address = new Uri($"http://{consulClientOption.IP}:{consulClientOption.Port}/"); + c.Datacenter = consulClientOption.Datacenter; + })) { - ID = $"{consulRegisterOption.IP}-{consulRegisterOption.Port}-{Guid.NewGuid()}",//唯一Id - Name = consulRegisterOption.GroupName,//组名称-Group - Address = consulRegisterOption.IP, - Port = consulRegisterOption.Port, - Tags = new string[] { consulRegisterOption.Tag }, - Check = new AgentServiceCheck() + client.Agent.ServiceRegister(new AgentServiceRegistration() { - Interval = TimeSpan.FromSeconds(consulRegisterOption.Interval), - HTTP = $"http://{consulRegisterOption.IP}:{consulRegisterOption.Port}{consulRegisterOption.HealthCheckUrl}", - Timeout = TimeSpan.FromSeconds(consulRegisterOption.Timeout), - DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(consulRegisterOption.DeregisterCriticalServiceAfter) - } - }).Wait(); - Console.WriteLine($"{JsonConvert.SerializeObject(consulRegisterOption)} 完成注册"); + ID = $"{consulRegisterOption.IP}-{consulRegisterOption.Port}-{Guid.NewGuid()}",//唯一Id + Name = consulRegisterOption.GroupName,//组名称-Group + Address = consulRegisterOption.IP, + Port = consulRegisterOption.Port, + Tags = new string[] { consulRegisterOption.Tag }, + Check = new AgentServiceCheck() + { + Interval = TimeSpan.FromSeconds(consulRegisterOption.Interval), + HTTP = $"http://{consulRegisterOption.IP}:{consulRegisterOption.Port}{consulRegisterOption.HealthCheckUrl}", + Timeout = TimeSpan.FromSeconds(consulRegisterOption.Timeout), + DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(consulRegisterOption.DeregisterCriticalServiceAfter) + } + }).Wait(); + Console.WriteLine($"{JsonConvert.SerializeObject(consulRegisterOption)} 完成注册"); + } } } - } } diff --git a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/CorsExtension.cs b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/CorsExtension.cs index 457944dc..d82443e4 100644 --- a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/CorsExtension.cs +++ b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/CorsExtension.cs @@ -12,21 +12,28 @@ namespace Yi.Framework.WebCore.MiddlewareExtend { public static IServiceCollection AddCorsService(this IServiceCollection services) { - services.AddCors(options => options.AddPolicy("CorsPolicy",//解决跨域问题 - builder => - { - builder.AllowAnyMethod() - .SetIsOriginAllowed(_ => true) - .AllowAnyHeader() - .AllowCredentials(); - })); + if (Appsettings.appBool("Cors_Enabled")) + { + + services.AddCors(options => options.AddPolicy("CorsPolicy",//解决跨域问题 + builder => + { + builder.AllowAnyMethod() + .SetIsOriginAllowed(_ => true) + .AllowAnyHeader() + .AllowCredentials(); + })); + } return services; } public static void UseCorsService(this IApplicationBuilder app) { - app.UseCors("CorsPolicy"); + if (Appsettings.appBool("Cors_Enabled")) + { + app.UseCors("CorsPolicy"); + } } } diff --git a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/DbExtend.cs b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/DbExtend.cs new file mode 100644 index 00000000..53458505 --- /dev/null +++ b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/DbExtend.cs @@ -0,0 +1,23 @@ +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Yi.Framework.Common.IOCOptions; +using Yi.Framework.Model; +using Yi.Framework.Model.ModelFactory; + +namespace Yi.Framework.WebCore.MiddlewareExtend +{ + public static class DbExtend + { + public static IServiceCollection AddDbService(this IServiceCollection services) + { + DbContextFactory.MutiDB_Enabled = Appsettings.appBool("MutiDB_Enabled"); + DataContext.DbSelect = Appsettings.app("DbSelect"); + services.Configure(Appsettings.appConfiguration("DbConn")); + return services; + } + } +} diff --git a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/DbSeedInitExtend.cs b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/DbSeedInitExtend.cs index 24219d1c..8d8d2d82 100644 --- a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/DbSeedInitExtend.cs +++ b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/DbSeedInitExtend.cs @@ -7,24 +7,29 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using Yi.Framework.Model.DbInit; +using Yi.Framework.Model.ModelFactory; namespace Yi.Framework.WebCore.MiddlewareExtend { public static class DbSeedInitExtend { private static readonly ILog log = LogManager.GetLogger(typeof(DbSeedInitExtend)); - public static void UseDbSeedInitService(this IApplicationBuilder app, DbContext _Db) + public static void UseDbSeedInitService(this IApplicationBuilder app, IDbContextFactory _DbFactory) { - if (app == null) throw new ArgumentNullException(nameof(app)); - try + if (Appsettings.appBool("DbSeed_Enabled")) { - DataSeed.SeedAsync(_Db).Wait(); - } - catch (Exception e) - { - log.Error($"Error occured seeding the Database.\n{e.Message}"); - throw; + if (app == null) throw new ArgumentNullException(nameof(app)); + + try + { + DataSeed.SeedAsync(_DbFactory).Wait(); + } + catch (Exception e) + { + log.Error($"Error occured seeding the Database.\n{e.Message}"); + throw; + } } } } diff --git a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/HealthCheckExtension.cs b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/HealthCheckExtension.cs index 7c49c1bd..0a489f8a 100644 --- a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/HealthCheckExtension.cs +++ b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/HealthCheckExtension.cs @@ -22,12 +22,17 @@ namespace Yi.Framework.WebCore.MiddlewareExtend /// public static void UseHealthCheckMiddleware(this IApplicationBuilder app, string checkPath = "/Health") { - app.Map(checkPath, applicationBuilder => applicationBuilder.Run(async context => + if (Appsettings.appBool("HealthCheck_Enabled")) { - Console.WriteLine($"This is Health Check"); - context.Response.StatusCode = (int)HttpStatusCode.OK; - await context.Response.WriteAsync("OK"); - })); + app.Map(checkPath, applicationBuilder => applicationBuilder.Run(async context => + { + Console.WriteLine($"This is Health Check"); + context.Response.StatusCode = (int)HttpStatusCode.OK; + await context.Response.WriteAsync("OK"); + })); + } + + } } diff --git a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/IocExtension.cs b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/IocExtension.cs index 216faa48..b7d73f4f 100644 --- a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/IocExtension.cs +++ b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/IocExtension.cs @@ -5,6 +5,7 @@ using Microsoft.Extensions.DependencyInjection; using System; using System.IO; using Yi.Framework.Model; +using Yi.Framework.Model.ModelFactory; namespace Yi.Framework.WebCore.MiddlewareExtend { @@ -19,13 +20,10 @@ namespace Yi.Framework.WebCore.MiddlewareExtend //配置文件使用配置 #endregion services.AddSingleton(new Appsettings(configuration)); - #region //数据库配置 #endregion - services.AddScoped(); - - + services.AddTransient(); return services; } diff --git a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/MysqlExtension.cs b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/MysqlExtension.cs deleted file mode 100644 index c8e799c0..00000000 --- a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/MysqlExtension.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.IO; -using Yi.Framework.Common.IOCOptions; - -namespace Yi.Framework.WebCore.MiddlewareExtend -{ - /// - /// 数据库扩展 - /// - public static class MysqlExtension - { - public static IServiceCollection AddMysqlService(this IServiceCollection services) - { - services.Configure(Appsettings.appConfiguration("MysqlConn")); - return services; - } - } -} diff --git a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/RabbitMQExtension.cs b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/RabbitMQExtension.cs index 54f63136..46b276cf 100644 --- a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/RabbitMQExtension.cs +++ b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/RabbitMQExtension.cs @@ -14,8 +14,12 @@ namespace Yi.Framework.WebCore.MiddlewareExtend { public static IServiceCollection AddRabbitMQService(this IServiceCollection services) { - services.Configure(Appsettings.appConfiguration("RabbitConn")); + if (Appsettings.appBool("RabbitMQ_Enabled")) + { + services.Configure(Appsettings.appConfiguration("RabbitConn")); + } return services; + } } } diff --git a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/RedisExtension.cs b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/RedisExtension.cs index 4cfbec69..6a9826ce 100644 --- a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/RedisExtension.cs +++ b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/RedisExtension.cs @@ -14,7 +14,10 @@ namespace Yi.Framework.WebCore.MiddlewareExtend { public static IServiceCollection AddRedisService(this IServiceCollection services) { - services.Configure(Appsettings.appConfiguration("RedisConn")); + if (Appsettings.appBool("Redis_Enabled")) + { + services.Configure(Appsettings.appConfiguration("RedisConn")); + } return services; } } diff --git a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/SqliteExtension.cs b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/SqliteExtension.cs deleted file mode 100644 index fec73a51..00000000 --- a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/SqliteExtension.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.IO; -using Yi.Framework.Common.IOCOptions; - -namespace Yi.Framework.WebCore.MiddlewareExtend -{ - /// - /// 数据库扩展 - /// - public static class SqliteExtension - { - public static IServiceCollection AddSqliteService(this IServiceCollection services) - { - services.Configure(Appsettings.appConfiguration("SqliteConn")); - return services; - } - } -} diff --git a/Yi.Framework/Yi.Framework.WebCore/Utility/CustomAutofacModule.cs b/Yi.Framework/Yi.Framework.WebCore/Utility/CustomAutofacModule.cs index c989edba..7db7d8f2 100644 --- a/Yi.Framework/Yi.Framework.WebCore/Utility/CustomAutofacModule.cs +++ b/Yi.Framework/Yi.Framework.WebCore/Utility/CustomAutofacModule.cs @@ -10,6 +10,7 @@ using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; +using Yi.Framework.Model.ModelFactory; using Yi.Framework.WebCore.Utility; using Module = Autofac.Module; @@ -19,6 +20,9 @@ namespace Yi.Framework.WebCore.Utility { protected override void Load(ContainerBuilder containerBuilder) { + + containerBuilder.RegisterType().As().InstancePerDependency().EnableInterfaceInterceptors(); + var basePath = AppContext.BaseDirectory; var servicesDllFile = Path.Combine(basePath, "Yi.Framework.Service.dll"); if (!(File.Exists(servicesDllFile))) @@ -41,7 +45,7 @@ namespace Yi.Framework.WebCore.Utility //containerBuilder.RegisterGeneric(typeof(BaseService<>)).As(typeof(IBaseService<>)).InstancePerDependency().EnableInterfaceInterceptors(); - + }