配置文件开关,数据库读写分离
This commit is contained in:
@@ -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;
|
||||
|
||||
@@ -28,7 +28,7 @@ namespace Yi.Framework.ApiMicroservice
|
||||
#region
|
||||
//Apollo<6C><6F><EFBFBD><EFBFBD>
|
||||
#endregion
|
||||
//configurationBuilder.AddApolloService("Yi");
|
||||
configurationBuilder.AddApolloService("Yi");
|
||||
})
|
||||
.ConfigureLogging(loggingBuilder =>
|
||||
{
|
||||
@@ -38,7 +38,7 @@ namespace Yi.Framework.ApiMicroservice
|
||||
})
|
||||
.ConfigureWebHostDefaults(webBuilder =>
|
||||
{
|
||||
webBuilder.UseStartup<Startup>().UseUrls("https://*:44329");
|
||||
webBuilder.UseStartup<Startup>();
|
||||
}).UseServiceProviderFactory(new AutofacServiceProviderFactory());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
//<2F><><EFBFBD>ݿ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
#endregion
|
||||
services.AddSqliteService();
|
||||
|
||||
#region
|
||||
//MySql<71><6C><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
#endregion
|
||||
services.AddMysqlService();
|
||||
services.AddDbService();
|
||||
|
||||
#region
|
||||
//Redis<69><73><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
#endregion
|
||||
//services.AddRedisService();
|
||||
services.AddRedisService();
|
||||
|
||||
#region
|
||||
//RabbitMQ<4D><51><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
#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
|
||||
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ע<EFBFBD><D7A2>
|
||||
#endregion
|
||||
//app.UseHealthCheckMiddleware();
|
||||
app.UseHealthCheckMiddleware();
|
||||
|
||||
#region
|
||||
//<2F><>Ȩע<C8A8><D7A2>
|
||||
@@ -134,12 +130,12 @@ namespace Yi.Framework.ApiMicroservice
|
||||
#region
|
||||
//Consul<75><6C><EFBFBD><EFBFBD>ע<EFBFBD><D7A2>
|
||||
#endregion
|
||||
//app.UseConsulService();
|
||||
app.UseConsulService();
|
||||
|
||||
#region
|
||||
//<2F><><EFBFBD>ݿ<EFBFBD><DDBF><EFBFBD><EFBFBD><EFBFBD>ע<EFBFBD><D7A2>
|
||||
#endregion
|
||||
app.UseDbSeedInitService(_Db);
|
||||
app.UseDbSeedInitService(_DbFactory);
|
||||
|
||||
#region
|
||||
//Endpointsע<73><D7A2>
|
||||
|
||||
@@ -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",
|
||||
|
||||
16
Yi.Framework/Yi.Framework.Common/Const/DbConst.cs
Normal file
16
Yi.Framework/Yi.Framework.Common/Const/DbConst.cs
Normal file
@@ -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";
|
||||
}
|
||||
}
|
||||
@@ -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<string> ReadUrl { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ namespace Yi.Framework.Common.IOCOptions
|
||||
{
|
||||
public class SqliteOptions
|
||||
{
|
||||
public string Url { get; set; }
|
||||
public string WriteUrl { get; set; }
|
||||
public List<string> ReadUrl { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace Yi.Framework.Common.Enum
|
||||
{
|
||||
public enum WriteAndReadEnum
|
||||
{
|
||||
Write, //主库操作
|
||||
Read //从库操作
|
||||
}
|
||||
}
|
||||
@@ -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<MySqlConnOptions> _optionsMonitor;
|
||||
private readonly string _connStr;
|
||||
//private readonly IOptionsMonitor<MySqlConnOptions> _optionsMonitor;
|
||||
private string _connStr;
|
||||
public static string DbSelect = DbConst.Mysql;
|
||||
//public DataContext(IOptionsMonitor<MySqlConnOptions> 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<MySqlConnOptions> 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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<user>().Any())
|
||||
{
|
||||
await _Db.Set<user>().AddAsync(new user
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
100
Yi.Framework/Yi.Framework.Model/ModelFactory/DbContextFactory.cs
Normal file
100
Yi.Framework/Yi.Framework.Model/ModelFactory/DbContextFactory.cs
Normal file
@@ -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
|
||||
|
||||
/// <summary>
|
||||
///能把链接信息也注入进来
|
||||
///需要IOptionsMonitor
|
||||
/// </summary>
|
||||
/// <param name="context"></param>
|
||||
public DbContextFactory(DbContext context, IOptionsMonitor<DbConnOptions> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更换成主库连接
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
private void ToWrite()
|
||||
{
|
||||
string conn = _readAndWrite.WriteUrl;
|
||||
//_Context.Database.GetDbConnection().;
|
||||
_Context.ToWriteOrRead(conn);
|
||||
}
|
||||
|
||||
|
||||
private static int _iSeed = 0;
|
||||
|
||||
/// <summary>
|
||||
/// 更换成主库连接
|
||||
///
|
||||
/// ///策略---数据库查询的负载均衡
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
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()
|
||||
//{
|
||||
|
||||
//}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<T> : IBaseService<T> 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<T> GetEntityById(int id)
|
||||
|
||||
@@ -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<menu>,IMenuService
|
||||
{
|
||||
public MenuService(DbContext Db):base(Db){ }
|
||||
public MenuService(IDbContextFactory DbFactory):base(DbFactory){ }
|
||||
|
||||
public async Task<bool> DelListByUpdateAsync(List<int> _ids)
|
||||
{
|
||||
@@ -30,7 +31,7 @@ namespace Yi.Framework.Service
|
||||
|
||||
public partial class MouldService:BaseService<mould>,IMouldService
|
||||
{
|
||||
public MouldService(DbContext Db):base(Db){ }
|
||||
public MouldService(IDbContextFactory DbFactory):base(DbFactory){ }
|
||||
|
||||
public async Task<bool> DelListByUpdateAsync(List<int> _ids)
|
||||
{
|
||||
@@ -48,7 +49,7 @@ namespace Yi.Framework.Service
|
||||
|
||||
public partial class RoleService:BaseService<role>,IRoleService
|
||||
{
|
||||
public RoleService(DbContext Db):base(Db){ }
|
||||
public RoleService(IDbContextFactory DbFactory):base(DbFactory){ }
|
||||
|
||||
public async Task<bool> DelListByUpdateAsync(List<int> _ids)
|
||||
{
|
||||
@@ -66,7 +67,7 @@ namespace Yi.Framework.Service
|
||||
|
||||
public partial class UserService:BaseService<user>,IUserService
|
||||
{
|
||||
public UserService(DbContext Db):base(Db){ }
|
||||
public UserService(IDbContextFactory DbFactory):base(DbFactory){ }
|
||||
|
||||
public async Task<bool> DelListByUpdateAsync(List<int> _ids)
|
||||
{
|
||||
|
||||
@@ -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<bool> DelListByUpdateAsync(List<int> _ids)
|
||||
{
|
||||
|
||||
@@ -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<user>, IUserService
|
||||
{
|
||||
private IRoleService _roleService;
|
||||
public UserService(DbContext Db, IRoleService roleService) : base(Db)
|
||||
public UserService(IDbContextFactory DbFactory, IRoleService roleService) : base(DbFactory)
|
||||
{
|
||||
_roleService = roleService;
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ namespace Yi.Framework.WebCore
|
||||
/// <summary>
|
||||
/// appsettings.json操作类
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 递归获取配置信息数组
|
||||
/// </summary>
|
||||
|
||||
@@ -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
|
||||
/// <summary>
|
||||
|
||||
@@ -23,36 +23,39 @@ namespace Yi.Framework.WebCore.MiddlewareExtend
|
||||
/// <param name="app"></param>
|
||||
/// <param name="healthService"></param>
|
||||
/// <returns></returns>
|
||||
public static void UseConsulService(this IApplicationBuilder app)
|
||||
public static void UseConsulService(this IApplicationBuilder app)
|
||||
{
|
||||
var consulRegisterOption= Appsettings.app<ConsulRegisterOption>("ConsulRegisterOption");
|
||||
|
||||
var consulClientOption= Appsettings.app<ConsulClientOption>("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>("ConsulRegisterOption");
|
||||
|
||||
var consulClientOption = Appsettings.app<ConsulClientOption>("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)} 完成注册");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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<DbConnOptions>(Appsettings.appConfiguration("DbConn"));
|
||||
return services;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,12 +22,17 @@ namespace Yi.Framework.WebCore.MiddlewareExtend
|
||||
/// <returns></returns>
|
||||
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");
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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<DbContext, DataContext>();
|
||||
|
||||
|
||||
services.AddTransient<DbContext, DataContext>();
|
||||
return services;
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// 数据库扩展
|
||||
/// </summary>
|
||||
public static class MysqlExtension
|
||||
{
|
||||
public static IServiceCollection AddMysqlService(this IServiceCollection services)
|
||||
{
|
||||
services.Configure<MySqlConnOptions>(Appsettings.appConfiguration("MysqlConn"));
|
||||
return services;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,8 +14,12 @@ namespace Yi.Framework.WebCore.MiddlewareExtend
|
||||
{
|
||||
public static IServiceCollection AddRabbitMQService(this IServiceCollection services)
|
||||
{
|
||||
services.Configure<RabbitMQOptions>(Appsettings.appConfiguration("RabbitConn"));
|
||||
if (Appsettings.appBool("RabbitMQ_Enabled"))
|
||||
{
|
||||
services.Configure<RabbitMQOptions>(Appsettings.appConfiguration("RabbitConn"));
|
||||
}
|
||||
return services;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,10 @@ namespace Yi.Framework.WebCore.MiddlewareExtend
|
||||
{
|
||||
public static IServiceCollection AddRedisService(this IServiceCollection services)
|
||||
{
|
||||
services.Configure<RedisConnOptions>(Appsettings.appConfiguration("RedisConn"));
|
||||
if (Appsettings.appBool("Redis_Enabled"))
|
||||
{
|
||||
services.Configure<RedisConnOptions>(Appsettings.appConfiguration("RedisConn"));
|
||||
}
|
||||
return services;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// 数据库扩展
|
||||
/// </summary>
|
||||
public static class SqliteExtension
|
||||
{
|
||||
public static IServiceCollection AddSqliteService(this IServiceCollection services)
|
||||
{
|
||||
services.Configure<SqliteOptions>(Appsettings.appConfiguration("SqliteConn"));
|
||||
return services;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<DbContextFactory>().As<IDbContextFactory>().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();
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user