完成第一版本的ShardingCore x.6.x.x

This commit is contained in:
xuejiaming 2022-07-01 20:58:20 +08:00
parent a288c517ba
commit 78cd5f23b1
27 changed files with 408 additions and 261 deletions

View File

@ -1,74 +1,65 @@
// using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
// using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
// using System; using System;
// using System.Collections.Generic; using System.Collections.Generic;
// using System.Linq; using System.Linq;
// using System.Threading.Tasks; using System.Threading.Tasks;
// using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
// using Sample.MySql.DbContexts; using Sample.MySql.DbContexts;
// using Sample.MySql.Domain.Entities; using Sample.MySql.Domain.Entities;
// using ShardingCore.Core.PhysicTables; using ShardingCore.TableCreator;
// using ShardingCore.Core.VirtualTables;
// using ShardingCore.DbContexts.VirtualDbContexts; namespace Sample.MySql.Controllers
// using ShardingCore.Extensions; {
// using ShardingCore.TableCreator; [ApiController]
// [Route("[controller]/[action]")]
// namespace Sample.MySql.Controllers public class WeatherForecastController : ControllerBase
// { {
// [ApiController]
// [Route("[controller]/[action]")] private readonly DefaultShardingDbContext _defaultTableDbContext;
// public class WeatherForecastController : ControllerBase
// { public WeatherForecastController(DefaultShardingDbContext defaultTableDbContext)
// {
// private readonly DefaultTableDbContext _defaultTableDbContext; _defaultTableDbContext = defaultTableDbContext;
// private readonly IVirtualTableManager _virtualTableManager; }
// private readonly IShardingTableCreator _tableCreator;
// [HttpGet]
// public WeatherForecastController(DefaultTableDbContext defaultTableDbContext,IVirtualTableManager virtualTableManager, IShardingTableCreator tableCreator) public async Task<IActionResult> Get()
// { {
// _defaultTableDbContext = defaultTableDbContext;
// _virtualTableManager = virtualTableManager;
// _tableCreator = tableCreator; var result = await _defaultTableDbContext.Set<SysTest>().AnyAsync();
// } var result1 = await _defaultTableDbContext.Set<SysUserMod>().Where(o => o.Id == "2" || o.Id == "3").ToListAsync();
// var result2 = await _defaultTableDbContext.Set<SysUserLogByMonth>().Skip(1).Take(10).ToListAsync();
// [HttpGet] var shardingFirstOrDefaultAsync = await _defaultTableDbContext.Set<SysUserLogByMonth>().ToListAsync();
// public async Task<IActionResult> Get() var shardingCountAsync = await _defaultTableDbContext.Set<SysUserMod>().CountAsync();
// { var shardingCountAsyn2c = _defaultTableDbContext.Set<SysUserLogByMonth>().Count();
// var taleAllTails = _virtualTableManager.GetVirtualTable(typeof(SysUserLogByMonth)).GetTableAllTails();
// return Ok(result1);
// }
// var result = await _defaultTableDbContext.Set<SysTest>().AnyAsync(); // [HttpGet]
// var result1 = await _defaultTableDbContext.Set<SysUserMod>().Where(o => o.Id == "2" || o.Id == "3").ToShardingListAsync(); // public async Task<IActionResult> Get1()
// var result2 = await _defaultTableDbContext.Set<SysUserLogByMonth>().Skip(1).Take(10).ToShardingListAsync(); // {
// var shardingFirstOrDefaultAsync = await _defaultTableDbContext.Set<SysUserLogByMonth>().ShardingFirstOrDefaultAsync(); // var allVirtualTables = _virtualTableManager.GetAllVirtualTables();
// var shardingCountAsync = await _defaultTableDbContext.Set<SysUserMod>().ShardingCountAsync(); // foreach (var virtualTable in allVirtualTables)
// var shardingCountAsyn2c = _defaultTableDbContext.Set<SysUserLogByMonth>().ShardingCount(); // {
// // if (virtualTable.EntityType == typeof(SysUserLogByMonth))
// return Ok(result1); // {
// } // var now = DateTime.Now.Date.AddMonths(2);
// [HttpGet] // var tail = virtualTable.GetVirtualRoute().ShardingKeyToTail(now);
// public async Task<IActionResult> Get1() // try
// { // {
// var allVirtualTables = _virtualTableManager.GetAllVirtualTables(); // _virtualTableManager.AddPhysicTable(virtualTable, new DefaultPhysicTable(virtualTable, tail));
// foreach (var virtualTable in allVirtualTables) // _tableCreator.CreateTable<SysUserLogByMonth>(tail);
// { // }
// if (virtualTable.EntityType == typeof(SysUserLogByMonth)) // catch (Exception e)
// { // {
// var now = DateTime.Now.Date.AddMonths(2); // //ignore
// var tail = virtualTable.GetVirtualRoute().ShardingKeyToTail(now); // Console.WriteLine(e);
// try // }
// { // }
// _virtualTableManager.AddPhysicTable(virtualTable, new DefaultPhysicTable(virtualTable, tail)); // }
// _tableCreator.CreateTable<SysUserLogByMonth>(tail); // return Ok();
// } // }
// catch (Exception e) }
// { }
// //ignore
// Console.WriteLine(e);
// }
// }
// }
// return Ok();
// }
// }
// }

View File

@ -7,6 +7,10 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.6">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="6.0.1" /> <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="6.0.1" />
</ItemGroup> </ItemGroup>

View File

@ -1,6 +1,5 @@
using Sample.MySql.Domain.Entities; using Sample.MySql.Domain.Entities;
using ShardingCore.Core.EntityMetadatas; using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Core.PhysicTables;
using ShardingCore.VirtualRoutes.Mods; using ShardingCore.VirtualRoutes.Mods;
namespace Sample.MySql.Shardings namespace Sample.MySql.Shardings

View File

@ -1,16 +1,9 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MySqlConnector;
using Sample.MySql.DbContexts; using Sample.MySql.DbContexts;
using Sample.MySql.Shardings; using Sample.MySql.Shardings;
using ShardingCore; using ShardingCore;
using ShardingCore.Helpers; using ShardingCore.Core;
using ShardingCore.TableExists; using ShardingCore.Extensions;
namespace Sample.MySql namespace Sample.MySql
{ {
@ -42,41 +35,72 @@ namespace Sample.MySql
// op.AddShardingTableRoute<SysUserSalaryVirtualTableRoute>(); // op.AddShardingTableRoute<SysUserSalaryVirtualTableRoute>();
// }); // });
services.AddShardingDbContext<DefaultShardingDbContext>() services.AddSingleton<IShardingRuntimeContext>(sp =>
.AddEntityConfig(o => {
{ return new ShardingRuntimeBuilder<DefaultShardingDbContext>()
o.CreateDataBaseOnlyOnStart = true; .UseRouteConfig(o =>
o.CreateShardingTableOnStart = true;
o.EnsureCreatedWithOutShardingTable = true;
o.IgnoreCreateTableError = true;
o.AddShardingTableRoute<SysUserLogByMonthRoute>();
o.AddShardingTableRoute<SysUserModVirtualTableRoute>();
o.AddShardingDataSourceRoute<SysUserModVirtualDataSourceRoute>();
o.UseShardingQuery((conStr, builder) =>
{ {
builder.UseMySql(conStr, new MySqlServerVersion(new Version()) o.AddShardingTableRoute<SysUserLogByMonthRoute>();
,b=>b.EnableRetryOnFailure() o.AddShardingTableRoute<SysUserModVirtualTableRoute>();
) // o.AddShardingDataSourceRoute<SysUserModVirtualDataSourceRoute>();
.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking).UseLoggerFactory(efLogger); }).UseConfig(o =>
//builder.UseMySql(conStr, new MySqlServerVersion(new Version())); {
}); o.UseShardingQuery((conStr,builder)=>
o.UseShardingTransaction((connection, builder) => {
{ builder.UseMySql(conStr, new MySqlServerVersion(new Version())
builder.UseMySql(connection, new MySqlServerVersion(new Version()) // ,b=>b.EnableRetryOnFailure()
,b=>b.EnableRetryOnFailure()
) )
.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking).UseLoggerFactory(efLogger); .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking).UseLoggerFactory(efLogger);
}); });
}) o.UseShardingTransaction((connection, builder) =>
.AddConfig(op => {
{ builder.UseMySql(connection, new MySqlServerVersion(new Version())
op.ConfigId = "c0"; // ,b=>b.EnableRetryOnFailure()
op.AddDefaultDataSource("ds0", )
"server=127.0.0.1;port=3306;database=dbdbd0;userid=root;password=root;"); .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking).UseLoggerFactory(efLogger);
});
o.AddDefaultDataSource("ds0",
"server=127.0.0.1;port=3306;database=dbdbd0;userid=root;password=root;");
//op.AddDefaultDataSource("ds0", "server=127.0.0.1;port=3306;database=db2;userid=root;password=L6yBtV6qNENrwBy7;") })
op.ReplaceTableEnsureManager(sp=>new MySqlTableEnsureManager<DefaultShardingDbContext>()); .Build(sp);
}).EnsureConfig(); });
services.AddDbContext<DefaultShardingDbContext>(ShardingCoreExtension.UseDefaultSharding<DefaultShardingDbContext>);
// services.AddShardingDbContext<DefaultShardingDbContext>()
// .AddEntityConfig(o =>
// {
// o.CreateDataBaseOnlyOnStart = true;
// o.CreateShardingTableOnStart = true;
// o.EnsureCreatedWithOutShardingTable = true;
// o.IgnoreCreateTableError = true;
// o.AddShardingTableRoute<SysUserLogByMonthRoute>();
// o.AddShardingTableRoute<SysUserModVirtualTableRoute>();
// o.AddShardingDataSourceRoute<SysUserModVirtualDataSourceRoute>();
// o.UseShardingQuery((conStr, builder) =>
// {
// builder.UseMySql(conStr, new MySqlServerVersion(new Version())
// ,b=>b.EnableRetryOnFailure()
// )
// .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking).UseLoggerFactory(efLogger);
// //builder.UseMySql(conStr, new MySqlServerVersion(new Version()));
// });
// o.UseShardingTransaction((connection, builder) =>
// {
// builder.UseMySql(connection, new MySqlServerVersion(new Version())
// ,b=>b.EnableRetryOnFailure()
// )
// .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking).UseLoggerFactory(efLogger);
// });
// })
// .AddConfig(op =>
// {
// op.ConfigId = "c0";
// op.AddDefaultDataSource("ds0",
// "server=127.0.0.1;port=3306;database=dbdbd0;userid=root;password=root;");
//
// //op.AddDefaultDataSource("ds0", "server=127.0.0.1;port=3306;database=db2;userid=root;password=L6yBtV6qNENrwBy7;")
// op.ReplaceTableEnsureManager(sp=>new MySqlTableEnsureManager<DefaultShardingDbContext>());
// }).EnsureConfig();
} }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
@ -88,20 +112,20 @@ namespace Sample.MySql
app.UseDeveloperExceptionPage(); app.UseDeveloperExceptionPage();
} }
app.UseShardingCore(); // app.UseShardingCore();
//
//
using (var serviceScope = app.ApplicationServices.CreateScope()) // using (var serviceScope = app.ApplicationServices.CreateScope())
{ // {
var defaultShardingDbContext = serviceScope.ServiceProvider.GetService<DefaultShardingDbContext>(); // var defaultShardingDbContext = serviceScope.ServiceProvider.GetService<DefaultShardingDbContext>();
} // }
//
Console.WriteLine("------------------"); // Console.WriteLine("------------------");
using (var serviceScope = app.ApplicationServices.CreateScope()) // using (var serviceScope = app.ApplicationServices.CreateScope())
{ // {
var defaultShardingDbContext = serviceScope.ServiceProvider.GetService<DefaultShardingDbContext>(); // var defaultShardingDbContext = serviceScope.ServiceProvider.GetService<DefaultShardingDbContext>();
} // }
Console.WriteLine("------------------"); // Console.WriteLine("------------------");
app.UseRouting(); app.UseRouting();
app.UseAuthorization(); app.UseAuthorization();

View File

@ -1,11 +1,4 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using ShardingCore.Core; using ShardingCore.Core;
using ShardingCore.Core.EntityMetadatas; using ShardingCore.Core.EntityMetadatas;
@ -36,9 +29,9 @@ namespace ShardingCore.Bootstrappers
/// </summary> /// </summary>
/// <typeparam name="TShardingDbContext"></typeparam> /// <typeparam name="TShardingDbContext"></typeparam>
/// <typeparam name="TEntity"></typeparam> /// <typeparam name="TEntity"></typeparam>
public class EntityMetadataInitializer<TShardingDbContext,TEntity>: IEntityMetadataInitializer where TShardingDbContext:DbContext,IShardingDbContext where TEntity:class public class EntityMetadataInitializer<TEntity>: IEntityMetadataInitializer where TEntity:class
{ {
private static readonly ILogger<EntityMetadataInitializer<TShardingDbContext, TEntity>> _logger=InternalLoggerFactory.CreateLogger<EntityMetadataInitializer<TShardingDbContext,TEntity>>(); private static readonly ILogger<EntityMetadataInitializer<TEntity>> _logger=InternalLoggerFactory.CreateLogger<EntityMetadataInitializer<TEntity>>();
// private const string QueryFilter = "QueryFilter"; // private const string QueryFilter = "QueryFilter";
// private readonly IEntityType _entityType; // private readonly IEntityType _entityType;
// private readonly string _virtualTableName; // private readonly string _virtualTableName;
@ -80,7 +73,7 @@ namespace ShardingCore.Bootstrappers
/// <exception cref="ShardingCoreInvalidOperationException"></exception> /// <exception cref="ShardingCoreInvalidOperationException"></exception>
public void Initialize() public void Initialize()
{ {
var entityMetadata = new EntityMetadata(_shardingEntityType, typeof(TShardingDbContext)); var entityMetadata = new EntityMetadata(_shardingEntityType);
if (!_entityMetadataManager.AddEntityMetadata(entityMetadata)) if (!_entityMetadataManager.AddEntityMetadata(entityMetadata))
throw new ShardingCoreInvalidOperationException($"repeat add entity metadata {_shardingEntityType.FullName}"); throw new ShardingCoreInvalidOperationException($"repeat add entity metadata {_shardingEntityType.FullName}");
//设置标签 //设置标签
@ -105,9 +98,6 @@ namespace ShardingCore.Bootstrappers
} }
if (_shardingRouteConfigOptions.TryGetVirtualTableRoute<TEntity>(out var virtualTableRouteType)) if (_shardingRouteConfigOptions.TryGetVirtualTableRoute<TEntity>(out var virtualTableRouteType))
{ {
if (!typeof(TShardingDbContext).IsShardingTableDbContext())
throw new ShardingCoreInvalidOperationException(
$"{typeof(TShardingDbContext)} is not impl {nameof(IShardingTableDbContext)},not support sharding table");
var entityMetadataTableBuilder = EntityMetadataTableBuilder<TEntity>.CreateEntityMetadataTableBuilder(entityMetadata); var entityMetadataTableBuilder = EntityMetadataTableBuilder<TEntity>.CreateEntityMetadataTableBuilder(entityMetadata);
//配置属性分表信息 //配置属性分表信息
EntityMetadataHelper.Configure(entityMetadataTableBuilder); EntityMetadataHelper.Configure(entityMetadataTableBuilder);

View File

@ -22,15 +22,15 @@ namespace ShardingCore.Bootstrappers
{ {
private readonly ILogger<ShardingBootstrapper> _logger; private readonly ILogger<ShardingBootstrapper> _logger;
private readonly IShardingProvider _shardingProvider; private readonly IShardingProvider _shardingProvider;
private readonly IDbContextTypeCollector _dbContextTypeCollector; private readonly IShardingDbContextBootstrapper _shardingDbContextBootstrapper;
private readonly IJobManager _jobManager; private readonly IJobManager _jobManager;
private readonly DoOnlyOnce _doOnlyOnce = new DoOnlyOnce(); private readonly DoOnlyOnce _doOnlyOnce = new DoOnlyOnce();
public ShardingBootstrapper(IShardingProvider shardingProvider,IDbContextTypeCollector dbContextTypeCollector,IJobManager jobManager) public ShardingBootstrapper(IShardingProvider shardingProvider,IShardingDbContextBootstrapper shardingDbContextBootstrapper,IJobManager jobManager)
{ {
_logger = InternalLoggerFactory.DefaultFactory.CreateLogger<ShardingBootstrapper>(); _logger = InternalLoggerFactory.DefaultFactory.CreateLogger<ShardingBootstrapper>();
_shardingProvider = shardingProvider; _shardingProvider = shardingProvider;
_dbContextTypeCollector = dbContextTypeCollector; _shardingDbContextBootstrapper = shardingDbContextBootstrapper;
_jobManager = jobManager; _jobManager = jobManager;
} }
/// <summary> /// <summary>
@ -42,11 +42,8 @@ namespace ShardingCore.Bootstrappers
return; return;
_logger.LogDebug("sharding core starting......"); _logger.LogDebug("sharding core starting......");
var instanceType = typeof(ShardingDbContextBootstrapper<>).GetGenericType0(_dbContextTypeCollector.ShardingDbContextType); _shardingDbContextBootstrapper.Initialize();
var instance = (IShardingDbContextBootstrapper)_shardingProvider.CreateInstance(instanceType); _logger.LogDebug($"sharding core complete init");
_logger.LogDebug($"{_dbContextTypeCollector.ShardingDbContextType} start init......");
instance.Initialize();
_logger.LogDebug($"{_dbContextTypeCollector.ShardingDbContextType} complete init");
if (_jobManager != null && _jobManager.HasAnyJob()) if (_jobManager != null && _jobManager.HasAnyJob())
{ {
@ -55,6 +52,7 @@ namespace ShardingCore.Bootstrappers
await _shardingProvider.GetRequiredService<JobRunnerService>().StartAsync(); await _shardingProvider.GetRequiredService<JobRunnerService>().StartAsync();
}, TaskCreationOptions.LongRunning); }, TaskCreationOptions.LongRunning);
} }
_logger.LogDebug("sharding core running......");
} }
} }

View File

@ -35,8 +35,7 @@ namespace ShardingCore.Bootstrappers
/// <summary> /// <summary>
/// 分片具体DbContext初始化器 /// 分片具体DbContext初始化器
/// </summary> /// </summary>
public class ShardingDbContextBootstrapper<TShardingDbContext> : IShardingDbContextBootstrapper public class ShardingDbContextBootstrapper: IShardingDbContextBootstrapper
where TShardingDbContext : DbContext, IShardingDbContext
{ {
private readonly IShardingProvider _shardingProvider; private readonly IShardingProvider _shardingProvider;
private readonly IShardingRouteConfigOptions _routeConfigOptions; private readonly IShardingRouteConfigOptions _routeConfigOptions;
@ -44,8 +43,6 @@ namespace ShardingCore.Bootstrappers
private readonly IParallelTableManager _parallelTableManager; private readonly IParallelTableManager _parallelTableManager;
// private readonly ITrackerManager<TShardingDbContext> _trackerManager;
private readonly Type _shardingDbContextType;
public ShardingDbContextBootstrapper( public ShardingDbContextBootstrapper(
IShardingProvider shardingProvider, IShardingProvider shardingProvider,
@ -54,7 +51,6 @@ namespace ShardingCore.Bootstrappers
IParallelTableManager parallelTableManager IParallelTableManager parallelTableManager
) )
{ {
_shardingDbContextType = typeof(TShardingDbContext);
_shardingProvider = shardingProvider; _shardingProvider = shardingProvider;
_routeConfigOptions = routeConfigOptions; _routeConfigOptions = routeConfigOptions;
_entityMetadataManager = entityMetadataManager; _entityMetadataManager = entityMetadataManager;
@ -78,7 +74,7 @@ namespace ShardingCore.Bootstrappers
foreach (var entityType in shardingEntities) foreach (var entityType in shardingEntities)
{ {
var entityMetadataInitializerType = var entityMetadataInitializerType =
typeof(EntityMetadataInitializer<,>).GetGenericType1(_shardingDbContextType, entityType); typeof(EntityMetadataInitializer<>).GetGenericType0(entityType);
var entityMetadataInitializer =(IEntityMetadataInitializer)_shardingProvider.CreateInstance(entityMetadataInitializerType); var entityMetadataInitializer =(IEntityMetadataInitializer)_shardingProvider.CreateInstance(entityMetadataInitializerType);
entityMetadataInitializer.Initialize(); entityMetadataInitializer.Initialize();

View File

@ -16,10 +16,9 @@ namespace ShardingCore.Core.EntityMetadatas
/// </summary> /// </summary>
public class EntityMetadata public class EntityMetadata
{private const string QueryFilter = "QueryFilter"; {private const string QueryFilter = "QueryFilter";
public EntityMetadata(Type entityType, Type shardingDbContextType) public EntityMetadata(Type entityType)
{ {
EntityType = entityType; EntityType = entityType;
ShardingDbContextType = shardingDbContextType;
ShardingDataSourceProperties = new Dictionary<string, PropertyInfo>(); ShardingDataSourceProperties = new Dictionary<string, PropertyInfo>();
ShardingTableProperties = new Dictionary<string, PropertyInfo>(); ShardingTableProperties = new Dictionary<string, PropertyInfo>();
} }
@ -28,8 +27,6 @@ namespace ShardingCore.Core.EntityMetadatas
/// </summary> /// </summary>
public Type EntityType { get; } public Type EntityType { get; }
public Type ShardingDbContextType { get; }
/// <summary> /// <summary>
/// 是否多数据源 /// 是否多数据源
/// </summary> /// </summary>

View File

@ -50,15 +50,6 @@ namespace ShardingCore.Core.ShardingConfigurations
/// 忽略建表时的错误 /// 忽略建表时的错误
/// </summary> /// </summary>
public bool? IgnoreCreateTableError { get; set; } = false; public bool? IgnoreCreateTableError { get; set; } = false;
/// <summary>
/// 添加分表路由
/// </summary>
/// <typeparam name="TRoute"></typeparam>
public void AddShardingDataSourceRoute<TRoute>() where TRoute : IVirtualDataSourceRoute
{
var routeType = typeof(TRoute);
AddShardingDataSourceRoute(routeType);
}
public bool ThrowIfQueryRouteNotMatch { get; set; } = true; public bool ThrowIfQueryRouteNotMatch { get; set; } = true;
@ -80,15 +71,6 @@ namespace ShardingCore.Core.ShardingConfigurations
_virtualDataSourceRoutes.Add(shardingEntityType, routeType); _virtualDataSourceRoutes.Add(shardingEntityType, routeType);
} }
} }
/// <summary>
/// 添加分表路由
/// </summary>
/// <typeparam name="TRoute"></typeparam>
public void AddShardingTableRoute<TRoute>() where TRoute : IVirtualTableRoute
{
var routeType = typeof(TRoute);
AddShardingTableRoute(routeType);
}
public void AddShardingTableRoute(Type routeType) public void AddShardingTableRoute(Type routeType)
{ {
if (!routeType.IsIVirtualTableRoute()) if (!routeType.IsIVirtualTableRoute())

View File

@ -54,9 +54,9 @@ namespace ShardingCore.Core
{ {
if (isInited) if (isInited)
return; return;
isInited = true;
_serviceProvider = _serviceMap.BuildServiceProvider(); _serviceProvider = _serviceMap.BuildServiceProvider();
_serviceProvider.GetRequiredService<IShardingBootstrapper>().Start(); _serviceProvider.GetRequiredService<IShardingBootstrapper>().Start();
isInited = true;
} }
} }
@ -126,6 +126,7 @@ namespace ShardingCore.Core
lock (INIT_MODEL) lock (INIT_MODEL)
{ {
if(isInitModeled) return; if(isInitModeled) return;
isInitModeled = true;
var entityMetadataManager = GetService<IEntityMetadataManager>(); var entityMetadataManager = GetService<IEntityMetadataManager>();
var entityTypes = dbContext.Model.GetEntityTypes(); var entityTypes = dbContext.Model.GetEntityTypes();
foreach (var entityType in entityTypes) foreach (var entityType in entityTypes)
@ -152,7 +153,7 @@ namespace ShardingCore.Core
} }
private void CheckIfNotBuild() private void CheckIfNotBuild()
{ {
if (isInited) if (!isInited)
throw new InvalidOperationException("sharding runtime not init"); throw new InvalidOperationException("sharding runtime not init");
} }

View File

@ -19,7 +19,7 @@ namespace ShardingCore.Core.VirtualRoutes.DataSourceRoutes.RouteRuleEngine
* @Ver: 1.0 * @Ver: 1.0
* @Email: 326308290@qq.com * @Email: 326308290@qq.com
*/ */
public class DataSourceRouteRuleEngine<TShardingDbContext> : IDataSourceRouteRuleEngine<TShardingDbContext> where TShardingDbContext : DbContext, IShardingDbContext public class DataSourceRouteRuleEngine: IDataSourceRouteRuleEngine
{ {
private readonly IEntityMetadataManager _entityMetadataManager; private readonly IEntityMetadataManager _entityMetadataManager;

View File

@ -18,14 +18,14 @@ namespace ShardingCore.Core.VirtualRoutes.DataSourceRoutes.RouteRuleEngine
/// <summary> /// <summary>
/// 分库路由引擎工程 /// 分库路由引擎工程
/// </summary> /// </summary>
public class DataSourceRouteRuleEngineFactory<TShardingDbContext>: IDataSourceRouteRuleEngineFactory<TShardingDbContext> where TShardingDbContext : DbContext, IShardingDbContext public class DataSourceRouteRuleEngineFactory: IDataSourceRouteRuleEngineFactory
{ {
private readonly IDataSourceRouteRuleEngine<TShardingDbContext> _dataSourceRouteRuleEngine; private readonly IDataSourceRouteRuleEngine _dataSourceRouteRuleEngine;
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
/// <param name="dataSourceRouteRuleEngine"></param> /// <param name="dataSourceRouteRuleEngine"></param>
public DataSourceRouteRuleEngineFactory(IDataSourceRouteRuleEngine<TShardingDbContext> dataSourceRouteRuleEngine) public DataSourceRouteRuleEngineFactory(IDataSourceRouteRuleEngine dataSourceRouteRuleEngine)
{ {
_dataSourceRouteRuleEngine = dataSourceRouteRuleEngine; _dataSourceRouteRuleEngine = dataSourceRouteRuleEngine;
} }

View File

@ -18,9 +18,4 @@ namespace ShardingCore.Core.VirtualRoutes.DataSourceRoutes.RouteRuleEngine
DataSourceRouteResult Route(DataSourceRouteRuleContext routeRuleContext); DataSourceRouteResult Route(DataSourceRouteRuleContext routeRuleContext);
} }
public interface IDataSourceRouteRuleEngine<TShardingDbContext> : IDataSourceRouteRuleEngine
where TShardingDbContext : DbContext, IShardingDbContext
{
}
} }

View File

@ -20,8 +20,4 @@ namespace ShardingCore.Core.VirtualRoutes.DataSourceRoutes.RouteRuleEngine
DataSourceRouteResult Route(IQueryable queryable, IShardingDbContext shardingDbContext, Dictionary<Type, IQueryable> queryEntities); DataSourceRouteResult Route(IQueryable queryable, IShardingDbContext shardingDbContext, Dictionary<Type, IQueryable> queryEntities);
//DataSourceRouteResult Route(DataSourceRouteRuleContext ruleContext); //DataSourceRouteResult Route(DataSourceRouteRuleContext ruleContext);
} }
public interface IDataSourceRouteRuleEngineFactory<TShardingDbContext> : IDataSourceRouteRuleEngineFactory
where TShardingDbContext : DbContext, IShardingDbContext
{
}
} }

View File

@ -89,6 +89,10 @@ namespace ShardingCore.Core.VirtualRoutes.TableRoutes.RoutingRuleEngine
if (tableRouteResults.IsNotEmpty()) if (tableRouteResults.IsNotEmpty())
{ {
dataSourceCount++; dataSourceCount++;
if (tableRouteResults.Count > 1)
{
isCrossTable = true;
}
foreach (var tableRouteResult in tableRouteResults) foreach (var tableRouteResult in tableRouteResults)
{ {
if (tableRouteResult.ReplaceTables.Count > 1) if (tableRouteResult.ReplaceTables.Count > 1)

View File

@ -0,0 +1,118 @@
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using ShardingCore.Core;
namespace ShardingCore.EFCores.OptionsExtensions
{
/*
* @Author: xjm
* @Description:
* @Date: 2021/10/17 20:27:12
* @Ver: 1.0
* @Email: 326308290@qq.com
*/
#if EFCORE6
public class ShardingOptionsExtension : IDbContextOptionsExtension
{
private readonly IShardingRuntimeContext _shardingRuntimeContext;
public ShardingOptionsExtension(IShardingRuntimeContext shardingRuntimeContext)
{
_shardingRuntimeContext = shardingRuntimeContext;
}
public void ApplyServices(IServiceCollection services)
{
services.AddSingleton<IShardingRuntimeContext>(sp => _shardingRuntimeContext);
}
public void Validate(IDbContextOptions options)
{
}
public DbContextOptionsExtensionInfo Info => new ShardingWrapDbContextOptionsExtensionInfo(this);
private class ShardingWrapDbContextOptionsExtensionInfo : DbContextOptionsExtensionInfo
{
public ShardingWrapDbContextOptionsExtensionInfo(IDbContextOptionsExtension extension) : base(extension)
{
}
public override int GetServiceProviderHashCode() => 0;
public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other) => true;
public override void PopulateDebugInfo(IDictionary<string, string> debugInfo)
{
}
public override bool IsDatabaseProvider => false;
public override string LogFragment => "ShardingOptionsExtension";
}
}
#endif
#if EFCORE3 || EFCORE5
public class ShardingOptionsExtension: IDbContextOptionsExtension
{
private readonly IShardingRuntimeContext _shardingRuntimeContext;
public ShardingOptionsExtension(IShardingRuntimeContext shardingRuntimeContext)
{
_shardingRuntimeContext = shardingRuntimeContext;
}
public void ApplyServices(IServiceCollection services)
{
services.AddSingleton<IShardingRuntimeContext>(sp => _shardingRuntimeContext);
}
public void Validate(IDbContextOptions options)
{
}
public DbContextOptionsExtensionInfo Info => new ShardingWrapDbContextOptionsExtensionInfo(this);
private class ShardingWrapDbContextOptionsExtensionInfo : DbContextOptionsExtensionInfo
{
public ShardingWrapDbContextOptionsExtensionInfo(IDbContextOptionsExtension extension) : base(extension) { }
public override long GetServiceProviderHashCode() => 0;
public override void PopulateDebugInfo(IDictionary<string, string> debugInfo) { }
public override bool IsDatabaseProvider => false;
public override string LogFragment => "ShardingOptionsExtension";
}
}
#endif
#if EFCORE2
public class ShardingOptionsExtension: IDbContextOptionsExtension
{
private readonly IShardingRuntimeContext _shardingRuntimeContext;
public ShardingOptionsExtension(IShardingRuntimeContext shardingRuntimeContext)
{
_shardingRuntimeContext = shardingRuntimeContext;
}
public bool ApplyServices(IServiceCollection services)
{
services.AddSingleton<IShardingRuntimeContext>(sp => _shardingRuntimeContext);
return true;
}
public long GetServiceProviderHashCode() => 0;
public void Validate(IDbContextOptions options)
{
}
public string LogFragment => "ShardingOptionsExtension";
}
#endif
}

View File

@ -18,15 +18,12 @@ namespace ShardingCore.EFCores.OptionsExtensions
#if EFCORE6 #if EFCORE6
public class ShardingWrapOptionsExtension : IDbContextOptionsExtension public class ShardingWrapOptionsExtension : IDbContextOptionsExtension
{ {
private readonly IShardingRuntimeContext _shardingRuntimeContext;
public ShardingWrapOptionsExtension(IShardingRuntimeContext shardingRuntimeContext) public ShardingWrapOptionsExtension()
{ {
_shardingRuntimeContext = shardingRuntimeContext;
} }
public void ApplyServices(IServiceCollection services) public void ApplyServices(IServiceCollection services)
{ {
services.AddSingleton<IShardingRuntimeContext>(sp => _shardingRuntimeContext);
} }
public void Validate(IDbContextOptions options) public void Validate(IDbContextOptions options)

View File

@ -0,0 +1,30 @@
using ShardingCore.Core.ShardingConfigurations.Abstractions;
using ShardingCore.Core.VirtualRoutes.DataSourceRoutes;
using ShardingCore.Core.VirtualRoutes.TableRoutes;
namespace ShardingCore.Extensions
{
public static class ShardingRouteConfigOptionsExtension
{
/// <summary>
/// 添加分表路由
/// </summary>
/// <typeparam name="TRoute"></typeparam>
public static void AddShardingDataSourceRoute<TRoute>(this IShardingRouteConfigOptions options) where TRoute : IVirtualDataSourceRoute
{
var routeType = typeof(TRoute);
options.AddShardingDataSourceRoute(routeType);
}
/// <summary>
/// 添加分表路由
/// </summary>
/// <typeparam name="TRoute"></typeparam>
public static void AddShardingTableRoute<TRoute>(this IShardingRouteConfigOptions options) where TRoute : IVirtualTableRoute
{
var routeType = typeof(TRoute);
options.AddShardingTableRoute(routeType);
}
}
}

View File

@ -16,7 +16,7 @@ namespace ShardingCore.Sharding.Abstractions
StreamMergeContext Create(IMergeQueryCompilerContext mergeQueryCompilerContext); StreamMergeContext Create(IMergeQueryCompilerContext mergeQueryCompilerContext);
} }
public interface IStreamMergeContextFactory<TShardingDbContext> : IStreamMergeContextFactory where TShardingDbContext:DbContext,IShardingDbContext // public interface IStreamMergeContextFactory<TShardingDbContext> : IStreamMergeContextFactory where TShardingDbContext:DbContext,IShardingDbContext
{ // {
} // }
} }

View File

@ -82,6 +82,7 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors
/// shell dbcontext最外面的壳 /// shell dbcontext最外面的壳
/// </summary> /// </summary>
private readonly DbContext _shardingShellDbContext; private readonly DbContext _shardingShellDbContext;
private readonly IShardingRuntimeContext _shardingRuntimeContext;
/// <summary> /// <summary>
/// 数据库事务 /// 数据库事务
@ -118,11 +119,13 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors
IDbContextCreator dbContextCreator, IDbContextCreator dbContextCreator,
ActualConnectionStringManager actualConnectionStringManager) ActualConnectionStringManager actualConnectionStringManager)
{ {
var shardingDbContext = (IShardingDbContext)shardingShellDbContext;
DataSourceName = dataSourceName; DataSourceName = dataSourceName;
IsDefault = isDefault; IsDefault = isDefault;
_shardingShellDbContext = shardingShellDbContext; _shardingShellDbContext = shardingShellDbContext;
_shardingRuntimeContext = shardingDbContext.GetShardingRuntimeContext();
DbContextType = shardingShellDbContext.GetType(); DbContextType = shardingShellDbContext.GetType();
_virtualDataSource =((IShardingDbContext)shardingShellDbContext) _virtualDataSource =shardingDbContext
.GetVirtualDataSource(); .GetVirtualDataSource();
_dbContextCreator = dbContextCreator; _dbContextCreator = dbContextCreator;
_actualConnectionStringManager = actualConnectionStringManager; _actualConnectionStringManager = actualConnectionStringManager;
@ -149,7 +152,7 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors
try try
{ {
//先创建dbcontext option builder //先创建dbcontext option builder
var dbContextOptionsBuilder = CreateDbContextOptionBuilder(DbContextType); var dbContextOptionsBuilder = CreateDbContextOptionBuilder(DbContextType).UseShardingOptions(_shardingRuntimeContext);
if (IsDefault) if (IsDefault)
{ {

View File

@ -34,6 +34,7 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors
//private readonly ConcurrentDictionary<string, ConcurrentDictionary<string, DbContext>> _dbContextCaches = new ConcurrentDictionary<string, ConcurrentDictionary<string, DbContext>>(); //private readonly ConcurrentDictionary<string, ConcurrentDictionary<string, DbContext>> _dbContextCaches = new ConcurrentDictionary<string, ConcurrentDictionary<string, DbContext>>();
private readonly ConcurrentDictionary<string, IDataSourceDbContext> _dbContextCaches = new ConcurrentDictionary<string, IDataSourceDbContext>(); private readonly ConcurrentDictionary<string, IDataSourceDbContext> _dbContextCaches = new ConcurrentDictionary<string, IDataSourceDbContext>();
private readonly IShardingRuntimeContext _shardingRuntimeContext;
private readonly IVirtualDataSource _virtualDataSource; private readonly IVirtualDataSource _virtualDataSource;
private readonly ITableRouteManager _tableRouteManager; private readonly ITableRouteManager _tableRouteManager;
private readonly IDbContextCreator _dbContextCreator; private readonly IDbContextCreator _dbContextCreator;
@ -59,14 +60,14 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors
{ {
_shardingDbContext = shardingDbContext; _shardingDbContext = shardingDbContext;
//初始化 //初始化
var shardingRuntimeContext = shardingDbContext.GetRequireService<IShardingRuntimeContext>(); _shardingRuntimeContext = shardingDbContext.GetRequireService<IShardingRuntimeContext>();
shardingRuntimeContext.GetOrCreateShardingRuntimeModel(shardingDbContext); _shardingRuntimeContext.GetOrCreateShardingRuntimeModel(shardingDbContext);
_virtualDataSource = shardingRuntimeContext.GetVirtualDataSource(); _virtualDataSource = _shardingRuntimeContext.GetVirtualDataSource();
_tableRouteManager = shardingRuntimeContext.GetTableRouteManager(); _tableRouteManager = _shardingRuntimeContext.GetTableRouteManager();
_dbContextCreator = shardingRuntimeContext.GetDbContextCreator(); _dbContextCreator = _shardingRuntimeContext.GetDbContextCreator();
_entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager(); _entityMetadataManager = _shardingRuntimeContext.GetEntityMetadataManager();
_routeTailFactory = shardingRuntimeContext.GetRouteTailFactory(); _routeTailFactory = _shardingRuntimeContext.GetRouteTailFactory();
var shardingReadWriteManager = shardingRuntimeContext.GetShardingReadWriteManager(); var shardingReadWriteManager = _shardingRuntimeContext.GetShardingReadWriteManager();
_actualConnectionStringManager = new ActualConnectionStringManager(shardingReadWriteManager,_virtualDataSource); _actualConnectionStringManager = new ActualConnectionStringManager(shardingReadWriteManager,_virtualDataSource);
} }
@ -104,7 +105,7 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors
{ {
var dbContextOptionBuilder = DataSourceDbContext.CreateDbContextOptionBuilder(_shardingDbContext.GetType()); var dbContextOptionBuilder = DataSourceDbContext.CreateDbContextOptionBuilder(_shardingDbContext.GetType());
var connectionString = _actualConnectionStringManager.GetConnectionString(dataSourceName, false); var connectionString = _actualConnectionStringManager.GetConnectionString(dataSourceName, false);
_virtualDataSource.UseDbContextOptionsBuilder(connectionString, dbContextOptionBuilder); _virtualDataSource.UseDbContextOptionsBuilder(connectionString, dbContextOptionBuilder).UseShardingOptions(_shardingRuntimeContext);
return dbContextOptionBuilder.Options; return dbContextOptionBuilder.Options;
} }

View File

@ -18,7 +18,7 @@ namespace ShardingCore.Sharding
* @Date: Thursday, 28 January 2021 16:52:43 * @Date: Thursday, 28 January 2021 16:52:43
* @Email: 326308290@qq.com * @Email: 326308290@qq.com
*/ */
public class StreamMergeContextFactory<TShardingDbContext> : IStreamMergeContextFactory<TShardingDbContext> where TShardingDbContext:DbContext,IShardingDbContext public class StreamMergeContextFactory : IStreamMergeContextFactory
{ {
private readonly IRouteTailFactory _routeTailFactory; private readonly IRouteTailFactory _routeTailFactory;
private readonly IQueryableParseEngine _queryableParseEngine; private readonly IQueryableParseEngine _queryableParseEngine;

View File

@ -16,7 +16,6 @@ using ShardingCore.Core.VirtualRoutes;
using ShardingCore.Core.VirtualRoutes.DataSourceRoutes.RouteRuleEngine; using ShardingCore.Core.VirtualRoutes.DataSourceRoutes.RouteRuleEngine;
using ShardingCore.Core.VirtualRoutes.TableRoutes.RouteTails.Abstractions; using ShardingCore.Core.VirtualRoutes.TableRoutes.RouteTails.Abstractions;
using ShardingCore.Core.VirtualRoutes.TableRoutes.RoutingRuleEngine; using ShardingCore.Core.VirtualRoutes.TableRoutes.RoutingRuleEngine;
using ShardingCore.DIExtensions;
using ShardingCore.EFCores; using ShardingCore.EFCores;
using ShardingCore.EFCores.OptionsExtensions; using ShardingCore.EFCores.OptionsExtensions;
using ShardingCore.Jobs; using ShardingCore.Jobs;
@ -25,6 +24,7 @@ using ShardingCore.Sharding.Abstractions;
using ShardingCore.Sharding.ShardingQueryExecutors; using ShardingCore.Sharding.ShardingQueryExecutors;
using ShardingCore.TableCreator; using ShardingCore.TableCreator;
using System; using System;
using System.Diagnostics;
using ShardingCore.Bootstrappers; using ShardingCore.Bootstrappers;
using ShardingCore.Core; using ShardingCore.Core;
using ShardingCore.Core.DbContextCreator; using ShardingCore.Core.DbContextCreator;
@ -32,6 +32,8 @@ using ShardingCore.Core.QueryTrackers;
using ShardingCore.Core.UnionAllMergeShardingProviders; using ShardingCore.Core.UnionAllMergeShardingProviders;
using ShardingCore.Core.UnionAllMergeShardingProviders.Abstractions; using ShardingCore.Core.UnionAllMergeShardingProviders.Abstractions;
using ShardingCore.Core.VirtualDatabase.VirtualDataSources.Abstractions; using ShardingCore.Core.VirtualDatabase.VirtualDataSources.Abstractions;
using ShardingCore.Core.VirtualRoutes.Abstractions;
using ShardingCore.Core.VirtualRoutes.TableRoutes;
using ShardingCore.Sharding.MergeContexts; using ShardingCore.Sharding.MergeContexts;
using ShardingCore.Sharding.ParallelTables; using ShardingCore.Sharding.ParallelTables;
using ShardingCore.Sharding.Parsers; using ShardingCore.Sharding.Parsers;
@ -51,48 +53,60 @@ namespace ShardingCore
* @Date: Thursday, 28 January 2021 13:32:18 * @Date: Thursday, 28 January 2021 13:32:18
* @Email: 326308290@qq.com * @Email: 326308290@qq.com
*/ */
public static class DIExtension public static class ShardingCoreExtension
{ {
/// <summary> // /// <summary>
/// 添加ShardingCore配置和EntityFrameworkCore的<![CDATA[services.AddDbContext<TShardingDbContext>]]> // /// 添加ShardingCore配置和EntityFrameworkCore的<![CDATA[services.AddDbContext<TShardingDbContext>]]>
/// </summary> // /// </summary>
/// <typeparam name="TShardingDbContext"></typeparam> // /// <typeparam name="TShardingDbContext"></typeparam>
/// <param name="services"></param> // /// <param name="services"></param>
/// <param name="contextLifetime"></param> // /// <param name="contextLifetime"></param>
/// <param name="optionsLifetime"></param> // /// <param name="optionsLifetime"></param>
/// <returns></returns> // /// <returns></returns>
/// <exception cref="NotSupportedException"></exception> // /// <exception cref="NotSupportedException"></exception>
public static ShardingCoreConfigBuilder<TShardingDbContext> AddShardingDbContext<TShardingDbContext>(this IServiceCollection services, // public static ShardingCoreConfigBuilder<TShardingDbContext> AddShardingDbContext<TShardingDbContext>(this IServiceCollection services,
ServiceLifetime contextLifetime = ServiceLifetime.Scoped, // ServiceLifetime contextLifetime = ServiceLifetime.Scoped,
ServiceLifetime optionsLifetime = ServiceLifetime.Scoped) // ServiceLifetime optionsLifetime = ServiceLifetime.Scoped)
where TShardingDbContext : DbContext, IShardingDbContext // where TShardingDbContext : DbContext, IShardingDbContext
{ // {
if (contextLifetime == ServiceLifetime.Singleton) // if (contextLifetime == ServiceLifetime.Singleton)
throw new NotSupportedException($"{nameof(contextLifetime)}:{nameof(ServiceLifetime.Singleton)}"); // throw new NotSupportedException($"{nameof(contextLifetime)}:{nameof(ServiceLifetime.Singleton)}");
if (optionsLifetime == ServiceLifetime.Singleton) // if (optionsLifetime == ServiceLifetime.Singleton)
throw new NotSupportedException($"{nameof(optionsLifetime)}:{nameof(ServiceLifetime.Singleton)}"); // throw new NotSupportedException($"{nameof(optionsLifetime)}:{nameof(ServiceLifetime.Singleton)}");
services.AddDbContext<TShardingDbContext>(UseDefaultSharding<TShardingDbContext>, contextLifetime, optionsLifetime); // services.AddDbContext<TShardingDbContext>(UseDefaultSharding<TShardingDbContext>, contextLifetime, optionsLifetime);
return services.AddShardingConfigure<TShardingDbContext>(); // return services.AddShardingConfigure<TShardingDbContext>();
} // }
//
public static ShardingCoreConfigBuilder<TShardingDbContext> AddShardingConfigure<TShardingDbContext>(this IServiceCollection services) // public static ShardingCoreConfigBuilder<TShardingDbContext> AddShardingConfigure<TShardingDbContext>(this IServiceCollection services)
where TShardingDbContext : DbContext, IShardingDbContext // where TShardingDbContext : DbContext, IShardingDbContext
{ // {
//ShardingCoreHelper.CheckContextConstructors<TShardingDbContext>(); // //ShardingCoreHelper.CheckContextConstructors<TShardingDbContext>();
return new ShardingCoreConfigBuilder<TShardingDbContext>(services); // return new ShardingCoreConfigBuilder<TShardingDbContext>(services);
} // }
public static void UseDefaultSharding<TShardingDbContext>(IServiceProvider serviceProvider,DbContextOptionsBuilder dbContextOptionsBuilder) where TShardingDbContext : DbContext, IShardingDbContext public static void UseDefaultSharding<TShardingDbContext>(IServiceProvider serviceProvider,DbContextOptionsBuilder dbContextOptionsBuilder) where TShardingDbContext : DbContext, IShardingDbContext
{ {
var shardingRuntimeContext = serviceProvider.GetRequiredService<IShardingRuntimeContext>(); var shardingRuntimeContext = serviceProvider.GetRequiredService<IShardingRuntimeContext>();
// Stopwatch sp=Stopwatch.StartNew();
// for (int i = 0; i < 100000; i++)
// {
//
// var virtualDataSource1 = shardingRuntimeContext.GetVirtualDataSource();
//
// }
// sp.Stop();
// Console.WriteLine(sp.ElapsedMilliseconds);
var virtualDataSource = shardingRuntimeContext.GetVirtualDataSource(); var virtualDataSource = shardingRuntimeContext.GetVirtualDataSource();
var connectionString = virtualDataSource.GetConnectionString(virtualDataSource.DefaultDataSourceName); var connectionString = virtualDataSource.GetConnectionString(virtualDataSource.DefaultDataSourceName);
var contextOptionsBuilder = virtualDataSource.ConfigurationParams.UseDbContextOptionsBuilder(connectionString, dbContextOptionsBuilder).UseSharding<TShardingDbContext>(shardingRuntimeContext); var contextOptionsBuilder = virtualDataSource.ConfigurationParams.UseDbContextOptionsBuilder(connectionString, dbContextOptionsBuilder)
.UseSharding<TShardingDbContext>(shardingRuntimeContext);
virtualDataSource.ConfigurationParams.UseShellDbContextOptionBuilder(contextOptionsBuilder); virtualDataSource.ConfigurationParams.UseShellDbContextOptionBuilder(contextOptionsBuilder);
} }
internal static IServiceCollection AddInternalShardingCore<TShardingDbContext>(this IServiceCollection services) where TShardingDbContext : DbContext, IShardingDbContext internal static IServiceCollection AddInternalShardingCore<TShardingDbContext>(this IServiceCollection services) where TShardingDbContext : DbContext, IShardingDbContext
{ {
services.TryAddSingleton<ITableRouteManager, TableRouteManager>();
services.TryAddSingleton<IShardingDbContextBootstrapper, ShardingDbContextBootstrapper>();
services.TryAddSingleton<IVirtualDataSourceConfigurationParams, SimpleVirtualDataSourceConfigurationParams>(); services.TryAddSingleton<IVirtualDataSourceConfigurationParams, SimpleVirtualDataSourceConfigurationParams>();
//分表dbcontext创建 //分表dbcontext创建
services.TryAddSingleton<IDbContextCreator, ActivatorDbContextCreator<TShardingDbContext>>(); services.TryAddSingleton<IDbContextCreator, ActivatorDbContextCreator<TShardingDbContext>>();
@ -100,13 +114,13 @@ namespace ShardingCore
// services.TryAddSingleton<IDataSourceInitializer<TShardingDbContext>, DataSourceInitializer<TShardingDbContext>>(); // services.TryAddSingleton<IDataSourceInitializer<TShardingDbContext>, DataSourceInitializer<TShardingDbContext>>();
services.TryAddSingleton<ITrackerManager, TrackerManager>(); services.TryAddSingleton<ITrackerManager, TrackerManager>();
services.TryAddSingleton<IStreamMergeContextFactory<TShardingDbContext>, StreamMergeContextFactory<TShardingDbContext>>(); services.TryAddSingleton<IStreamMergeContextFactory, StreamMergeContextFactory>();
services.TryAddSingleton<IShardingTableCreator, ShardingTableCreator>(); services.TryAddSingleton<IShardingTableCreator, ShardingTableCreator>();
//虚拟数据源管理 //虚拟数据源管理
services.TryAddSingleton<IVirtualDataSource, VirtualDataSource>(); services.TryAddSingleton<IVirtualDataSource, VirtualDataSource>();
services.TryAddSingleton<IVirtualDataSourceRouteManager, VirtualDataSourceRouteManager>(); services.TryAddSingleton<IVirtualDataSourceRouteManager, VirtualDataSourceRouteManager>();
services.TryAddSingleton<IDataSourceRouteRuleEngine<TShardingDbContext>, DataSourceRouteRuleEngine<TShardingDbContext>>(); services.TryAddSingleton<IDataSourceRouteRuleEngine, DataSourceRouteRuleEngine>();
services.TryAddSingleton<IDataSourceRouteRuleEngineFactory<TShardingDbContext>, DataSourceRouteRuleEngineFactory<TShardingDbContext>>(); services.TryAddSingleton<IDataSourceRouteRuleEngineFactory, DataSourceRouteRuleEngineFactory>();
//读写分离链接创建工厂 //读写分离链接创建工厂
services.TryAddSingleton<IShardingReadWriteAccessor, ShardingReadWriteAccessor>(); services.TryAddSingleton<IShardingReadWriteAccessor, ShardingReadWriteAccessor>();
services.TryAddSingleton<IReadWriteConnectorFactory, ReadWriteConnectorFactory>(); services.TryAddSingleton<IReadWriteConnectorFactory, ReadWriteConnectorFactory>();
@ -155,24 +169,33 @@ namespace ShardingCore
} }
public static DbContextOptionsBuilder UseSharding<TShardingDbContext>(this DbContextOptionsBuilder optionsBuilder,IShardingRuntimeContext shardingRuntimeContext) where TShardingDbContext : DbContext, IShardingDbContext public static DbContextOptionsBuilder UseSharding<TShardingDbContext>(this DbContextOptionsBuilder optionsBuilder,IShardingRuntimeContext shardingRuntimeContext) where TShardingDbContext : DbContext, IShardingDbContext
{ {
return optionsBuilder.UseShardingWrapMark(shardingRuntimeContext) return optionsBuilder.UseShardingWrapMark().UseShardingOptions(shardingRuntimeContext)
.ReplaceService<IDbSetSource, ShardingDbSetSource>() .ReplaceService<IDbSetSource, ShardingDbSetSource>()
.ReplaceService<IQueryCompiler, ShardingQueryCompiler>() .ReplaceService<IQueryCompiler, ShardingQueryCompiler>()
.ReplaceService<IDbContextTransactionManager, ShardingRelationalTransactionManager<TShardingDbContext>>() .ReplaceService<IDbContextTransactionManager, ShardingRelationalTransactionManager<TShardingDbContext>>()
.ReplaceService<IRelationalTransactionFactory, ShardingRelationalTransactionFactory<TShardingDbContext>>(); .ReplaceService<IRelationalTransactionFactory, ShardingRelationalTransactionFactory<TShardingDbContext>>();
} }
public static DbContextOptionsBuilder UseShardingOptions(this DbContextOptionsBuilder optionsBuilder,IShardingRuntimeContext shardingRuntimeContext)
private static DbContextOptionsBuilder UseShardingWrapMark(this DbContextOptionsBuilder optionsBuilder,IShardingRuntimeContext shardingRuntimeContext)
{ {
var extension = optionsBuilder.CreateOrGetExtension(shardingRuntimeContext); var shardingOptionsExtension = optionsBuilder.CreateOrGetShardingOptionsExtension(shardingRuntimeContext);
((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(shardingOptionsExtension);
return optionsBuilder; return optionsBuilder;
} }
private static ShardingWrapOptionsExtension CreateOrGetExtension(this DbContextOptionsBuilder optionsBuilder,IShardingRuntimeContext shardingRuntimeContext)
private static DbContextOptionsBuilder UseShardingWrapMark(this DbContextOptionsBuilder optionsBuilder)
{
var shardingWrapExtension = optionsBuilder.CreateOrGetShardingWrapExtension();
((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(shardingWrapExtension);
return optionsBuilder;
}
private static ShardingWrapOptionsExtension CreateOrGetShardingWrapExtension(this DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.Options.FindExtension<ShardingWrapOptionsExtension>() ?? => optionsBuilder.Options.FindExtension<ShardingWrapOptionsExtension>() ??
new ShardingWrapOptionsExtension(shardingRuntimeContext); new ShardingWrapOptionsExtension();
private static ShardingOptionsExtension CreateOrGetShardingOptionsExtension(this DbContextOptionsBuilder optionsBuilder,IShardingRuntimeContext shardingRuntimeContext)
=> optionsBuilder.Options.FindExtension<ShardingOptionsExtension>() ??
new ShardingOptionsExtension(shardingRuntimeContext);
public static DbContextOptionsBuilder UseInnerDbContextSharding(this DbContextOptionsBuilder optionsBuilder) public static DbContextOptionsBuilder UseInnerDbContextSharding(this DbContextOptionsBuilder optionsBuilder)
{ {

View File

@ -67,7 +67,7 @@ namespace ShardingCore
shardingRuntimeContext.UseLogfactory(loggerFactory); shardingRuntimeContext.UseLogfactory(loggerFactory);
shardingRuntimeContext.AddServiceConfig(services => shardingRuntimeContext.AddServiceConfig(services =>
{ {
services.AddSingleton<IDbContextTypeCollector>(sp => new DbContextTypeCollector<TShardingDbContext>()); // services.AddSingleton<IDbContextTypeCollector>(sp => new DbContextTypeCollector<TShardingDbContext>());
services.AddSingleton<IShardingRouteConfigOptions>(sp => _shardingRouteConfigOptions); services.AddSingleton<IShardingRouteConfigOptions>(sp => _shardingRouteConfigOptions);
services.AddSingleton(sp => _shardingConfigOptions); services.AddSingleton(sp => _shardingConfigOptions);

View File

@ -26,7 +26,7 @@ namespace ShardingCore.VirtualRoutes.Abstractions
/// 不可以设置一样 /// 不可以设置一样
/// </summary> /// </summary>
public virtual string JobName => public virtual string JobName =>
$"{EntityMetadata?.ShardingDbContextType?.Name}:{EntityMetadata?.EntityType?.Name}"; $"{GetType().Name}:{EntityMetadata?.EntityType?.Name}";
/// <summary> /// <summary>
/// 是否需要自动创建按时间分表的路由 /// 是否需要自动创建按时间分表的路由

View File

@ -14,8 +14,7 @@ namespace ShardingCore.CommonTest
private readonly List<string> _allDataSources; private readonly List<string> _allDataSources;
public ShardingDataSourceMod() public ShardingDataSourceMod()
{ {
var entityMetadata = new EntityMetadata(typeof(TestEntity), nameof(TestEntity), typeof(ShardingDataSourceMod), var entityMetadata = new EntityMetadata(typeof(TestEntity));
new ReadOnlyCollection<PropertyInfo>(typeof(TestEntity).GetProperties().ToList()), null);
var entityMetadataDataSourceBuilder = EntityMetadataDataSourceBuilder<TestEntity>.CreateEntityMetadataDataSourceBuilder(entityMetadata); var entityMetadataDataSourceBuilder = EntityMetadataDataSourceBuilder<TestEntity>.CreateEntityMetadataDataSourceBuilder(entityMetadata);
entityMetadataDataSourceBuilder.ShardingProperty(o => o.Id); entityMetadataDataSourceBuilder.ShardingProperty(o => o.Id);
entityMetadata.CheckShardingDataSourceMetadata(); entityMetadata.CheckShardingDataSourceMetadata();

View File

@ -15,8 +15,7 @@ namespace ShardingCore.CommonTest
private readonly List<string> _allTables; private readonly List<string> _allTables;
public ShardingTableTime() public ShardingTableTime()
{ {
var entityMetadata = new EntityMetadata(typeof(TestTimeEntity), nameof(TestTimeEntity), typeof(ShardingDataSourceMod), var entityMetadata = new EntityMetadata(typeof(TestTimeEntity));
new ReadOnlyCollection<PropertyInfo>(typeof(TestTimeEntity).GetProperties().ToList()), null);
var entityMetadataTableBuilder = EntityMetadataTableBuilder<TestTimeEntity>.CreateEntityMetadataTableBuilder(entityMetadata); var entityMetadataTableBuilder = EntityMetadataTableBuilder<TestTimeEntity>.CreateEntityMetadataTableBuilder(entityMetadata);
entityMetadataTableBuilder.ShardingProperty(o => o.Time); entityMetadataTableBuilder.ShardingProperty(o => o.Time);
entityMetadata.CheckShardingTableMetadata(); entityMetadata.CheckShardingTableMetadata();