完成第一版本的ShardingCore x.6.x.x
This commit is contained in:
parent
a288c517ba
commit
78cd5f23b1
|
@ -1,74 +1,65 @@
|
|||
// using Microsoft.AspNetCore.Mvc;
|
||||
// using Microsoft.Extensions.Logging;
|
||||
// using System;
|
||||
// using System.Collections.Generic;
|
||||
// using System.Linq;
|
||||
// using System.Threading.Tasks;
|
||||
// using Microsoft.EntityFrameworkCore;
|
||||
// using Sample.MySql.DbContexts;
|
||||
// using Sample.MySql.Domain.Entities;
|
||||
// using ShardingCore.Core.PhysicTables;
|
||||
// using ShardingCore.Core.VirtualTables;
|
||||
// using ShardingCore.DbContexts.VirtualDbContexts;
|
||||
// using ShardingCore.Extensions;
|
||||
// using ShardingCore.TableCreator;
|
||||
//
|
||||
// namespace Sample.MySql.Controllers
|
||||
// {
|
||||
// [ApiController]
|
||||
// [Route("[controller]/[action]")]
|
||||
// public class WeatherForecastController : ControllerBase
|
||||
// {
|
||||
//
|
||||
// private readonly DefaultTableDbContext _defaultTableDbContext;
|
||||
// private readonly IVirtualTableManager _virtualTableManager;
|
||||
// private readonly IShardingTableCreator _tableCreator;
|
||||
//
|
||||
// public WeatherForecastController(DefaultTableDbContext defaultTableDbContext,IVirtualTableManager virtualTableManager, IShardingTableCreator tableCreator)
|
||||
// {
|
||||
// _defaultTableDbContext = defaultTableDbContext;
|
||||
// _virtualTableManager = virtualTableManager;
|
||||
// _tableCreator = tableCreator;
|
||||
// }
|
||||
//
|
||||
// [HttpGet]
|
||||
// public async Task<IActionResult> Get()
|
||||
// {
|
||||
// var taleAllTails = _virtualTableManager.GetVirtualTable(typeof(SysUserLogByMonth)).GetTableAllTails();
|
||||
//
|
||||
//
|
||||
// var result = await _defaultTableDbContext.Set<SysTest>().AnyAsync();
|
||||
// var result1 = await _defaultTableDbContext.Set<SysUserMod>().Where(o => o.Id == "2" || o.Id == "3").ToShardingListAsync();
|
||||
// var result2 = await _defaultTableDbContext.Set<SysUserLogByMonth>().Skip(1).Take(10).ToShardingListAsync();
|
||||
// var shardingFirstOrDefaultAsync = await _defaultTableDbContext.Set<SysUserLogByMonth>().ShardingFirstOrDefaultAsync();
|
||||
// var shardingCountAsync = await _defaultTableDbContext.Set<SysUserMod>().ShardingCountAsync();
|
||||
// var shardingCountAsyn2c = _defaultTableDbContext.Set<SysUserLogByMonth>().ShardingCount();
|
||||
//
|
||||
// return Ok(result1);
|
||||
// }
|
||||
// [HttpGet]
|
||||
// public async Task<IActionResult> Get1()
|
||||
// {
|
||||
// var allVirtualTables = _virtualTableManager.GetAllVirtualTables();
|
||||
// foreach (var virtualTable in allVirtualTables)
|
||||
// {
|
||||
// if (virtualTable.EntityType == typeof(SysUserLogByMonth))
|
||||
// {
|
||||
// var now = DateTime.Now.Date.AddMonths(2);
|
||||
// var tail = virtualTable.GetVirtualRoute().ShardingKeyToTail(now);
|
||||
// try
|
||||
// {
|
||||
// _virtualTableManager.AddPhysicTable(virtualTable, new DefaultPhysicTable(virtualTable, tail));
|
||||
// _tableCreator.CreateTable<SysUserLogByMonth>(tail);
|
||||
// }
|
||||
// catch (Exception e)
|
||||
// {
|
||||
// //ignore
|
||||
// Console.WriteLine(e);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// return Ok();
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Sample.MySql.DbContexts;
|
||||
using Sample.MySql.Domain.Entities;
|
||||
using ShardingCore.TableCreator;
|
||||
|
||||
namespace Sample.MySql.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("[controller]/[action]")]
|
||||
public class WeatherForecastController : ControllerBase
|
||||
{
|
||||
|
||||
private readonly DefaultShardingDbContext _defaultTableDbContext;
|
||||
|
||||
public WeatherForecastController(DefaultShardingDbContext defaultTableDbContext)
|
||||
{
|
||||
_defaultTableDbContext = defaultTableDbContext;
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Get()
|
||||
{
|
||||
|
||||
|
||||
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();
|
||||
var shardingFirstOrDefaultAsync = await _defaultTableDbContext.Set<SysUserLogByMonth>().ToListAsync();
|
||||
var shardingCountAsync = await _defaultTableDbContext.Set<SysUserMod>().CountAsync();
|
||||
var shardingCountAsyn2c = _defaultTableDbContext.Set<SysUserLogByMonth>().Count();
|
||||
|
||||
return Ok(result1);
|
||||
}
|
||||
// [HttpGet]
|
||||
// public async Task<IActionResult> Get1()
|
||||
// {
|
||||
// var allVirtualTables = _virtualTableManager.GetAllVirtualTables();
|
||||
// foreach (var virtualTable in allVirtualTables)
|
||||
// {
|
||||
// if (virtualTable.EntityType == typeof(SysUserLogByMonth))
|
||||
// {
|
||||
// var now = DateTime.Now.Date.AddMonths(2);
|
||||
// var tail = virtualTable.GetVirtualRoute().ShardingKeyToTail(now);
|
||||
// try
|
||||
// {
|
||||
// _virtualTableManager.AddPhysicTable(virtualTable, new DefaultPhysicTable(virtualTable, tail));
|
||||
// _tableCreator.CreateTable<SysUserLogByMonth>(tail);
|
||||
// }
|
||||
// catch (Exception e)
|
||||
// {
|
||||
// //ignore
|
||||
// Console.WriteLine(e);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// return Ok();
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,6 +7,10 @@
|
|||
</PropertyGroup>
|
||||
|
||||
<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" />
|
||||
</ItemGroup>
|
||||
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
using Sample.MySql.Domain.Entities;
|
||||
using ShardingCore.Core.EntityMetadatas;
|
||||
using ShardingCore.Core.PhysicTables;
|
||||
using ShardingCore.VirtualRoutes.Mods;
|
||||
|
||||
namespace Sample.MySql.Shardings
|
||||
|
|
|
@ -1,16 +1,9 @@
|
|||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using MySqlConnector;
|
||||
using Sample.MySql.DbContexts;
|
||||
using Sample.MySql.Shardings;
|
||||
using ShardingCore;
|
||||
using ShardingCore.Helpers;
|
||||
using ShardingCore.TableExists;
|
||||
using ShardingCore.Core;
|
||||
using ShardingCore.Extensions;
|
||||
|
||||
namespace Sample.MySql
|
||||
{
|
||||
|
@ -42,41 +35,72 @@ namespace Sample.MySql
|
|||
// op.AddShardingTableRoute<SysUserSalaryVirtualTableRoute>();
|
||||
// });
|
||||
|
||||
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) =>
|
||||
services.AddSingleton<IShardingRuntimeContext>(sp =>
|
||||
{
|
||||
return new ShardingRuntimeBuilder<DefaultShardingDbContext>()
|
||||
.UseRouteConfig(o =>
|
||||
{
|
||||
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) =>
|
||||
o.AddShardingTableRoute<SysUserLogByMonthRoute>();
|
||||
o.AddShardingTableRoute<SysUserModVirtualTableRoute>();
|
||||
// o.AddShardingDataSourceRoute<SysUserModVirtualDataSourceRoute>();
|
||||
}).UseConfig(o =>
|
||||
{
|
||||
builder.UseMySql(connection, new MySqlServerVersion(new Version())
|
||||
,b=>b.EnableRetryOnFailure()
|
||||
o.UseShardingQuery((conStr,builder)=>
|
||||
{
|
||||
builder.UseMySql(conStr, 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;");
|
||||
.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking).UseLoggerFactory(efLogger);
|
||||
});
|
||||
o.UseShardingTransaction((connection, builder) =>
|
||||
{
|
||||
builder.UseMySql(connection, new MySqlServerVersion(new Version())
|
||||
// ,b=>b.EnableRetryOnFailure()
|
||||
)
|
||||
.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>());
|
||||
}).EnsureConfig();
|
||||
})
|
||||
.Build(sp);
|
||||
});
|
||||
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.
|
||||
|
@ -88,20 +112,20 @@ namespace Sample.MySql
|
|||
app.UseDeveloperExceptionPage();
|
||||
}
|
||||
|
||||
app.UseShardingCore();
|
||||
|
||||
|
||||
using (var serviceScope = app.ApplicationServices.CreateScope())
|
||||
{
|
||||
var defaultShardingDbContext = serviceScope.ServiceProvider.GetService<DefaultShardingDbContext>();
|
||||
}
|
||||
|
||||
Console.WriteLine("------------------");
|
||||
using (var serviceScope = app.ApplicationServices.CreateScope())
|
||||
{
|
||||
var defaultShardingDbContext = serviceScope.ServiceProvider.GetService<DefaultShardingDbContext>();
|
||||
}
|
||||
Console.WriteLine("------------------");
|
||||
// app.UseShardingCore();
|
||||
//
|
||||
//
|
||||
// using (var serviceScope = app.ApplicationServices.CreateScope())
|
||||
// {
|
||||
// var defaultShardingDbContext = serviceScope.ServiceProvider.GetService<DefaultShardingDbContext>();
|
||||
// }
|
||||
//
|
||||
// Console.WriteLine("------------------");
|
||||
// using (var serviceScope = app.ApplicationServices.CreateScope())
|
||||
// {
|
||||
// var defaultShardingDbContext = serviceScope.ServiceProvider.GetService<DefaultShardingDbContext>();
|
||||
// }
|
||||
// Console.WriteLine("------------------");
|
||||
app.UseRouting();
|
||||
|
||||
app.UseAuthorization();
|
||||
|
|
|
@ -1,11 +1,4 @@
|
|||
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 ShardingCore.Core;
|
||||
using ShardingCore.Core.EntityMetadatas;
|
||||
|
@ -36,9 +29,9 @@ namespace ShardingCore.Bootstrappers
|
|||
/// </summary>
|
||||
/// <typeparam name="TShardingDbContext"></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 readonly IEntityType _entityType;
|
||||
// private readonly string _virtualTableName;
|
||||
|
@ -80,7 +73,7 @@ namespace ShardingCore.Bootstrappers
|
|||
/// <exception cref="ShardingCoreInvalidOperationException"></exception>
|
||||
public void Initialize()
|
||||
{
|
||||
var entityMetadata = new EntityMetadata(_shardingEntityType, typeof(TShardingDbContext));
|
||||
var entityMetadata = new EntityMetadata(_shardingEntityType);
|
||||
if (!_entityMetadataManager.AddEntityMetadata(entityMetadata))
|
||||
throw new ShardingCoreInvalidOperationException($"repeat add entity metadata {_shardingEntityType.FullName}");
|
||||
//设置标签
|
||||
|
@ -105,9 +98,6 @@ namespace ShardingCore.Bootstrappers
|
|||
}
|
||||
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);
|
||||
//配置属性分表信息
|
||||
EntityMetadataHelper.Configure(entityMetadataTableBuilder);
|
||||
|
|
|
@ -22,15 +22,15 @@ namespace ShardingCore.Bootstrappers
|
|||
{
|
||||
private readonly ILogger<ShardingBootstrapper> _logger;
|
||||
private readonly IShardingProvider _shardingProvider;
|
||||
private readonly IDbContextTypeCollector _dbContextTypeCollector;
|
||||
private readonly IShardingDbContextBootstrapper _shardingDbContextBootstrapper;
|
||||
private readonly IJobManager _jobManager;
|
||||
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>();
|
||||
_shardingProvider = shardingProvider;
|
||||
_dbContextTypeCollector = dbContextTypeCollector;
|
||||
_shardingDbContextBootstrapper = shardingDbContextBootstrapper;
|
||||
_jobManager = jobManager;
|
||||
}
|
||||
/// <summary>
|
||||
|
@ -42,11 +42,8 @@ namespace ShardingCore.Bootstrappers
|
|||
return;
|
||||
_logger.LogDebug("sharding core starting......");
|
||||
|
||||
var instanceType = typeof(ShardingDbContextBootstrapper<>).GetGenericType0(_dbContextTypeCollector.ShardingDbContextType);
|
||||
var instance = (IShardingDbContextBootstrapper)_shardingProvider.CreateInstance(instanceType);
|
||||
_logger.LogDebug($"{_dbContextTypeCollector.ShardingDbContextType} start init......");
|
||||
instance.Initialize();
|
||||
_logger.LogDebug($"{_dbContextTypeCollector.ShardingDbContextType} complete init");
|
||||
_shardingDbContextBootstrapper.Initialize();
|
||||
_logger.LogDebug($"sharding core complete init");
|
||||
|
||||
if (_jobManager != null && _jobManager.HasAnyJob())
|
||||
{
|
||||
|
@ -55,6 +52,7 @@ namespace ShardingCore.Bootstrappers
|
|||
await _shardingProvider.GetRequiredService<JobRunnerService>().StartAsync();
|
||||
}, TaskCreationOptions.LongRunning);
|
||||
}
|
||||
_logger.LogDebug("sharding core running......");
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -35,8 +35,7 @@ namespace ShardingCore.Bootstrappers
|
|||
/// <summary>
|
||||
/// 分片具体DbContext初始化器
|
||||
/// </summary>
|
||||
public class ShardingDbContextBootstrapper<TShardingDbContext> : IShardingDbContextBootstrapper
|
||||
where TShardingDbContext : DbContext, IShardingDbContext
|
||||
public class ShardingDbContextBootstrapper: IShardingDbContextBootstrapper
|
||||
{
|
||||
private readonly IShardingProvider _shardingProvider;
|
||||
private readonly IShardingRouteConfigOptions _routeConfigOptions;
|
||||
|
@ -44,8 +43,6 @@ namespace ShardingCore.Bootstrappers
|
|||
private readonly IParallelTableManager _parallelTableManager;
|
||||
|
||||
|
||||
// private readonly ITrackerManager<TShardingDbContext> _trackerManager;
|
||||
private readonly Type _shardingDbContextType;
|
||||
|
||||
public ShardingDbContextBootstrapper(
|
||||
IShardingProvider shardingProvider,
|
||||
|
@ -54,7 +51,6 @@ namespace ShardingCore.Bootstrappers
|
|||
IParallelTableManager parallelTableManager
|
||||
)
|
||||
{
|
||||
_shardingDbContextType = typeof(TShardingDbContext);
|
||||
_shardingProvider = shardingProvider;
|
||||
_routeConfigOptions = routeConfigOptions;
|
||||
_entityMetadataManager = entityMetadataManager;
|
||||
|
@ -78,7 +74,7 @@ namespace ShardingCore.Bootstrappers
|
|||
foreach (var entityType in shardingEntities)
|
||||
{
|
||||
var entityMetadataInitializerType =
|
||||
typeof(EntityMetadataInitializer<,>).GetGenericType1(_shardingDbContextType, entityType);
|
||||
typeof(EntityMetadataInitializer<>).GetGenericType0(entityType);
|
||||
|
||||
var entityMetadataInitializer =(IEntityMetadataInitializer)_shardingProvider.CreateInstance(entityMetadataInitializerType);
|
||||
entityMetadataInitializer.Initialize();
|
||||
|
|
|
@ -16,10 +16,9 @@ namespace ShardingCore.Core.EntityMetadatas
|
|||
/// </summary>
|
||||
public class EntityMetadata
|
||||
{private const string QueryFilter = "QueryFilter";
|
||||
public EntityMetadata(Type entityType, Type shardingDbContextType)
|
||||
public EntityMetadata(Type entityType)
|
||||
{
|
||||
EntityType = entityType;
|
||||
ShardingDbContextType = shardingDbContextType;
|
||||
ShardingDataSourceProperties = new Dictionary<string, PropertyInfo>();
|
||||
ShardingTableProperties = new Dictionary<string, PropertyInfo>();
|
||||
}
|
||||
|
@ -28,8 +27,6 @@ namespace ShardingCore.Core.EntityMetadatas
|
|||
/// </summary>
|
||||
public Type EntityType { get; }
|
||||
|
||||
public Type ShardingDbContextType { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否多数据源
|
||||
/// </summary>
|
||||
|
|
|
@ -50,15 +50,6 @@ namespace ShardingCore.Core.ShardingConfigurations
|
|||
/// 忽略建表时的错误
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
|
@ -80,15 +71,6 @@ namespace ShardingCore.Core.ShardingConfigurations
|
|||
_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)
|
||||
{
|
||||
if (!routeType.IsIVirtualTableRoute())
|
||||
|
|
|
@ -54,9 +54,9 @@ namespace ShardingCore.Core
|
|||
{
|
||||
if (isInited)
|
||||
return;
|
||||
isInited = true;
|
||||
_serviceProvider = _serviceMap.BuildServiceProvider();
|
||||
_serviceProvider.GetRequiredService<IShardingBootstrapper>().Start();
|
||||
isInited = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -126,6 +126,7 @@ namespace ShardingCore.Core
|
|||
lock (INIT_MODEL)
|
||||
{
|
||||
if(isInitModeled) return;
|
||||
isInitModeled = true;
|
||||
var entityMetadataManager = GetService<IEntityMetadataManager>();
|
||||
var entityTypes = dbContext.Model.GetEntityTypes();
|
||||
foreach (var entityType in entityTypes)
|
||||
|
@ -152,7 +153,7 @@ namespace ShardingCore.Core
|
|||
}
|
||||
private void CheckIfNotBuild()
|
||||
{
|
||||
if (isInited)
|
||||
if (!isInited)
|
||||
throw new InvalidOperationException("sharding runtime not init");
|
||||
}
|
||||
|
||||
|
|
|
@ -19,7 +19,7 @@ namespace ShardingCore.Core.VirtualRoutes.DataSourceRoutes.RouteRuleEngine
|
|||
* @Ver: 1.0
|
||||
* @Email: 326308290@qq.com
|
||||
*/
|
||||
public class DataSourceRouteRuleEngine<TShardingDbContext> : IDataSourceRouteRuleEngine<TShardingDbContext> where TShardingDbContext : DbContext, IShardingDbContext
|
||||
public class DataSourceRouteRuleEngine: IDataSourceRouteRuleEngine
|
||||
{
|
||||
private readonly IEntityMetadataManager _entityMetadataManager;
|
||||
|
||||
|
|
|
@ -18,14 +18,14 @@ namespace ShardingCore.Core.VirtualRoutes.DataSourceRoutes.RouteRuleEngine
|
|||
/// <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>
|
||||
/// ctor
|
||||
/// </summary>
|
||||
/// <param name="dataSourceRouteRuleEngine"></param>
|
||||
public DataSourceRouteRuleEngineFactory(IDataSourceRouteRuleEngine<TShardingDbContext> dataSourceRouteRuleEngine)
|
||||
public DataSourceRouteRuleEngineFactory(IDataSourceRouteRuleEngine dataSourceRouteRuleEngine)
|
||||
{
|
||||
_dataSourceRouteRuleEngine = dataSourceRouteRuleEngine;
|
||||
}
|
||||
|
|
|
@ -18,9 +18,4 @@ namespace ShardingCore.Core.VirtualRoutes.DataSourceRoutes.RouteRuleEngine
|
|||
DataSourceRouteResult Route(DataSourceRouteRuleContext routeRuleContext);
|
||||
}
|
||||
|
||||
public interface IDataSourceRouteRuleEngine<TShardingDbContext> : IDataSourceRouteRuleEngine
|
||||
where TShardingDbContext : DbContext, IShardingDbContext
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
@ -20,8 +20,4 @@ namespace ShardingCore.Core.VirtualRoutes.DataSourceRoutes.RouteRuleEngine
|
|||
DataSourceRouteResult Route(IQueryable queryable, IShardingDbContext shardingDbContext, Dictionary<Type, IQueryable> queryEntities);
|
||||
//DataSourceRouteResult Route(DataSourceRouteRuleContext ruleContext);
|
||||
}
|
||||
public interface IDataSourceRouteRuleEngineFactory<TShardingDbContext> : IDataSourceRouteRuleEngineFactory
|
||||
where TShardingDbContext : DbContext, IShardingDbContext
|
||||
{
|
||||
}
|
||||
}
|
||||
|
|
|
@ -89,6 +89,10 @@ namespace ShardingCore.Core.VirtualRoutes.TableRoutes.RoutingRuleEngine
|
|||
if (tableRouteResults.IsNotEmpty())
|
||||
{
|
||||
dataSourceCount++;
|
||||
if (tableRouteResults.Count > 1)
|
||||
{
|
||||
isCrossTable = true;
|
||||
}
|
||||
foreach (var tableRouteResult in tableRouteResults)
|
||||
{
|
||||
if (tableRouteResult.ReplaceTables.Count > 1)
|
||||
|
|
|
@ -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
|
||||
}
|
|
@ -18,15 +18,12 @@ namespace ShardingCore.EFCores.OptionsExtensions
|
|||
#if EFCORE6
|
||||
public class ShardingWrapOptionsExtension : IDbContextOptionsExtension
|
||||
{
|
||||
private readonly IShardingRuntimeContext _shardingRuntimeContext;
|
||||
|
||||
public ShardingWrapOptionsExtension(IShardingRuntimeContext shardingRuntimeContext)
|
||||
public ShardingWrapOptionsExtension()
|
||||
{
|
||||
_shardingRuntimeContext = shardingRuntimeContext;
|
||||
}
|
||||
public void ApplyServices(IServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<IShardingRuntimeContext>(sp => _shardingRuntimeContext);
|
||||
}
|
||||
|
||||
public void Validate(IDbContextOptions options)
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -16,7 +16,7 @@ namespace ShardingCore.Sharding.Abstractions
|
|||
StreamMergeContext Create(IMergeQueryCompilerContext mergeQueryCompilerContext);
|
||||
}
|
||||
|
||||
public interface IStreamMergeContextFactory<TShardingDbContext> : IStreamMergeContextFactory where TShardingDbContext:DbContext,IShardingDbContext
|
||||
{
|
||||
}
|
||||
// public interface IStreamMergeContextFactory<TShardingDbContext> : IStreamMergeContextFactory where TShardingDbContext:DbContext,IShardingDbContext
|
||||
// {
|
||||
// }
|
||||
}
|
|
@ -82,6 +82,7 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors
|
|||
/// shell dbcontext最外面的壳
|
||||
/// </summary>
|
||||
private readonly DbContext _shardingShellDbContext;
|
||||
private readonly IShardingRuntimeContext _shardingRuntimeContext;
|
||||
|
||||
/// <summary>
|
||||
/// 数据库事务
|
||||
|
@ -118,11 +119,13 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors
|
|||
IDbContextCreator dbContextCreator,
|
||||
ActualConnectionStringManager actualConnectionStringManager)
|
||||
{
|
||||
var shardingDbContext = (IShardingDbContext)shardingShellDbContext;
|
||||
DataSourceName = dataSourceName;
|
||||
IsDefault = isDefault;
|
||||
_shardingShellDbContext = shardingShellDbContext;
|
||||
_shardingRuntimeContext = shardingDbContext.GetShardingRuntimeContext();
|
||||
DbContextType = shardingShellDbContext.GetType();
|
||||
_virtualDataSource =((IShardingDbContext)shardingShellDbContext)
|
||||
_virtualDataSource =shardingDbContext
|
||||
.GetVirtualDataSource();
|
||||
_dbContextCreator = dbContextCreator;
|
||||
_actualConnectionStringManager = actualConnectionStringManager;
|
||||
|
@ -149,7 +152,7 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors
|
|||
try
|
||||
{
|
||||
//先创建dbcontext option builder
|
||||
var dbContextOptionsBuilder = CreateDbContextOptionBuilder(DbContextType);
|
||||
var dbContextOptionsBuilder = CreateDbContextOptionBuilder(DbContextType).UseShardingOptions(_shardingRuntimeContext);
|
||||
|
||||
if (IsDefault)
|
||||
{
|
||||
|
|
|
@ -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, IDataSourceDbContext> _dbContextCaches = new ConcurrentDictionary<string, IDataSourceDbContext>();
|
||||
private readonly IShardingRuntimeContext _shardingRuntimeContext;
|
||||
private readonly IVirtualDataSource _virtualDataSource;
|
||||
private readonly ITableRouteManager _tableRouteManager;
|
||||
private readonly IDbContextCreator _dbContextCreator;
|
||||
|
@ -59,14 +60,14 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors
|
|||
{
|
||||
_shardingDbContext = shardingDbContext;
|
||||
//初始化
|
||||
var shardingRuntimeContext = shardingDbContext.GetRequireService<IShardingRuntimeContext>();
|
||||
shardingRuntimeContext.GetOrCreateShardingRuntimeModel(shardingDbContext);
|
||||
_virtualDataSource = shardingRuntimeContext.GetVirtualDataSource();
|
||||
_tableRouteManager = shardingRuntimeContext.GetTableRouteManager();
|
||||
_dbContextCreator = shardingRuntimeContext.GetDbContextCreator();
|
||||
_entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager();
|
||||
_routeTailFactory = shardingRuntimeContext.GetRouteTailFactory();
|
||||
var shardingReadWriteManager = shardingRuntimeContext.GetShardingReadWriteManager();
|
||||
_shardingRuntimeContext = shardingDbContext.GetRequireService<IShardingRuntimeContext>();
|
||||
_shardingRuntimeContext.GetOrCreateShardingRuntimeModel(shardingDbContext);
|
||||
_virtualDataSource = _shardingRuntimeContext.GetVirtualDataSource();
|
||||
_tableRouteManager = _shardingRuntimeContext.GetTableRouteManager();
|
||||
_dbContextCreator = _shardingRuntimeContext.GetDbContextCreator();
|
||||
_entityMetadataManager = _shardingRuntimeContext.GetEntityMetadataManager();
|
||||
_routeTailFactory = _shardingRuntimeContext.GetRouteTailFactory();
|
||||
var shardingReadWriteManager = _shardingRuntimeContext.GetShardingReadWriteManager();
|
||||
_actualConnectionStringManager = new ActualConnectionStringManager(shardingReadWriteManager,_virtualDataSource);
|
||||
}
|
||||
|
||||
|
@ -104,7 +105,7 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors
|
|||
{
|
||||
var dbContextOptionBuilder = DataSourceDbContext.CreateDbContextOptionBuilder(_shardingDbContext.GetType());
|
||||
var connectionString = _actualConnectionStringManager.GetConnectionString(dataSourceName, false);
|
||||
_virtualDataSource.UseDbContextOptionsBuilder(connectionString, dbContextOptionBuilder);
|
||||
_virtualDataSource.UseDbContextOptionsBuilder(connectionString, dbContextOptionBuilder).UseShardingOptions(_shardingRuntimeContext);
|
||||
return dbContextOptionBuilder.Options;
|
||||
}
|
||||
|
||||
|
|
|
@ -18,7 +18,7 @@ namespace ShardingCore.Sharding
|
|||
* @Date: Thursday, 28 January 2021 16:52:43
|
||||
* @Email: 326308290@qq.com
|
||||
*/
|
||||
public class StreamMergeContextFactory<TShardingDbContext> : IStreamMergeContextFactory<TShardingDbContext> where TShardingDbContext:DbContext,IShardingDbContext
|
||||
public class StreamMergeContextFactory : IStreamMergeContextFactory
|
||||
{
|
||||
private readonly IRouteTailFactory _routeTailFactory;
|
||||
private readonly IQueryableParseEngine _queryableParseEngine;
|
||||
|
|
|
@ -16,7 +16,6 @@ using ShardingCore.Core.VirtualRoutes;
|
|||
using ShardingCore.Core.VirtualRoutes.DataSourceRoutes.RouteRuleEngine;
|
||||
using ShardingCore.Core.VirtualRoutes.TableRoutes.RouteTails.Abstractions;
|
||||
using ShardingCore.Core.VirtualRoutes.TableRoutes.RoutingRuleEngine;
|
||||
using ShardingCore.DIExtensions;
|
||||
using ShardingCore.EFCores;
|
||||
using ShardingCore.EFCores.OptionsExtensions;
|
||||
using ShardingCore.Jobs;
|
||||
|
@ -25,6 +24,7 @@ using ShardingCore.Sharding.Abstractions;
|
|||
using ShardingCore.Sharding.ShardingQueryExecutors;
|
||||
using ShardingCore.TableCreator;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using ShardingCore.Bootstrappers;
|
||||
using ShardingCore.Core;
|
||||
using ShardingCore.Core.DbContextCreator;
|
||||
|
@ -32,6 +32,8 @@ using ShardingCore.Core.QueryTrackers;
|
|||
using ShardingCore.Core.UnionAllMergeShardingProviders;
|
||||
using ShardingCore.Core.UnionAllMergeShardingProviders.Abstractions;
|
||||
using ShardingCore.Core.VirtualDatabase.VirtualDataSources.Abstractions;
|
||||
using ShardingCore.Core.VirtualRoutes.Abstractions;
|
||||
using ShardingCore.Core.VirtualRoutes.TableRoutes;
|
||||
using ShardingCore.Sharding.MergeContexts;
|
||||
using ShardingCore.Sharding.ParallelTables;
|
||||
using ShardingCore.Sharding.Parsers;
|
||||
|
@ -51,48 +53,60 @@ namespace ShardingCore
|
|||
* @Date: Thursday, 28 January 2021 13:32:18
|
||||
* @Email: 326308290@qq.com
|
||||
*/
|
||||
public static class DIExtension
|
||||
public static class ShardingCoreExtension
|
||||
{
|
||||
/// <summary>
|
||||
/// 添加ShardingCore配置和EntityFrameworkCore的<![CDATA[services.AddDbContext<TShardingDbContext>]]>
|
||||
/// </summary>
|
||||
/// <typeparam name="TShardingDbContext"></typeparam>
|
||||
/// <param name="services"></param>
|
||||
/// <param name="contextLifetime"></param>
|
||||
/// <param name="optionsLifetime"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="NotSupportedException"></exception>
|
||||
public static ShardingCoreConfigBuilder<TShardingDbContext> AddShardingDbContext<TShardingDbContext>(this IServiceCollection services,
|
||||
ServiceLifetime contextLifetime = ServiceLifetime.Scoped,
|
||||
ServiceLifetime optionsLifetime = ServiceLifetime.Scoped)
|
||||
where TShardingDbContext : DbContext, IShardingDbContext
|
||||
{
|
||||
if (contextLifetime == ServiceLifetime.Singleton)
|
||||
throw new NotSupportedException($"{nameof(contextLifetime)}:{nameof(ServiceLifetime.Singleton)}");
|
||||
if (optionsLifetime == ServiceLifetime.Singleton)
|
||||
throw new NotSupportedException($"{nameof(optionsLifetime)}:{nameof(ServiceLifetime.Singleton)}");
|
||||
services.AddDbContext<TShardingDbContext>(UseDefaultSharding<TShardingDbContext>, contextLifetime, optionsLifetime);
|
||||
return services.AddShardingConfigure<TShardingDbContext>();
|
||||
}
|
||||
|
||||
public static ShardingCoreConfigBuilder<TShardingDbContext> AddShardingConfigure<TShardingDbContext>(this IServiceCollection services)
|
||||
where TShardingDbContext : DbContext, IShardingDbContext
|
||||
{
|
||||
//ShardingCoreHelper.CheckContextConstructors<TShardingDbContext>();
|
||||
return new ShardingCoreConfigBuilder<TShardingDbContext>(services);
|
||||
}
|
||||
// /// <summary>
|
||||
// /// 添加ShardingCore配置和EntityFrameworkCore的<![CDATA[services.AddDbContext<TShardingDbContext>]]>
|
||||
// /// </summary>
|
||||
// /// <typeparam name="TShardingDbContext"></typeparam>
|
||||
// /// <param name="services"></param>
|
||||
// /// <param name="contextLifetime"></param>
|
||||
// /// <param name="optionsLifetime"></param>
|
||||
// /// <returns></returns>
|
||||
// /// <exception cref="NotSupportedException"></exception>
|
||||
// public static ShardingCoreConfigBuilder<TShardingDbContext> AddShardingDbContext<TShardingDbContext>(this IServiceCollection services,
|
||||
// ServiceLifetime contextLifetime = ServiceLifetime.Scoped,
|
||||
// ServiceLifetime optionsLifetime = ServiceLifetime.Scoped)
|
||||
// where TShardingDbContext : DbContext, IShardingDbContext
|
||||
// {
|
||||
// if (contextLifetime == ServiceLifetime.Singleton)
|
||||
// throw new NotSupportedException($"{nameof(contextLifetime)}:{nameof(ServiceLifetime.Singleton)}");
|
||||
// if (optionsLifetime == ServiceLifetime.Singleton)
|
||||
// throw new NotSupportedException($"{nameof(optionsLifetime)}:{nameof(ServiceLifetime.Singleton)}");
|
||||
// services.AddDbContext<TShardingDbContext>(UseDefaultSharding<TShardingDbContext>, contextLifetime, optionsLifetime);
|
||||
// return services.AddShardingConfigure<TShardingDbContext>();
|
||||
// }
|
||||
//
|
||||
// public static ShardingCoreConfigBuilder<TShardingDbContext> AddShardingConfigure<TShardingDbContext>(this IServiceCollection services)
|
||||
// where TShardingDbContext : DbContext, IShardingDbContext
|
||||
// {
|
||||
// //ShardingCoreHelper.CheckContextConstructors<TShardingDbContext>();
|
||||
// return new ShardingCoreConfigBuilder<TShardingDbContext>(services);
|
||||
// }
|
||||
|
||||
public static void UseDefaultSharding<TShardingDbContext>(IServiceProvider serviceProvider,DbContextOptionsBuilder dbContextOptionsBuilder) where TShardingDbContext : DbContext, IShardingDbContext
|
||||
{
|
||||
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 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);
|
||||
}
|
||||
internal static IServiceCollection AddInternalShardingCore<TShardingDbContext>(this IServiceCollection services) where TShardingDbContext : DbContext, IShardingDbContext
|
||||
{
|
||||
services.TryAddSingleton<ITableRouteManager, TableRouteManager>();
|
||||
services.TryAddSingleton<IShardingDbContextBootstrapper, ShardingDbContextBootstrapper>();
|
||||
services.TryAddSingleton<IVirtualDataSourceConfigurationParams, SimpleVirtualDataSourceConfigurationParams>();
|
||||
//分表dbcontext创建
|
||||
services.TryAddSingleton<IDbContextCreator, ActivatorDbContextCreator<TShardingDbContext>>();
|
||||
|
@ -100,13 +114,13 @@ namespace ShardingCore
|
|||
|
||||
// services.TryAddSingleton<IDataSourceInitializer<TShardingDbContext>, DataSourceInitializer<TShardingDbContext>>();
|
||||
services.TryAddSingleton<ITrackerManager, TrackerManager>();
|
||||
services.TryAddSingleton<IStreamMergeContextFactory<TShardingDbContext>, StreamMergeContextFactory<TShardingDbContext>>();
|
||||
services.TryAddSingleton<IStreamMergeContextFactory, StreamMergeContextFactory>();
|
||||
services.TryAddSingleton<IShardingTableCreator, ShardingTableCreator>();
|
||||
//虚拟数据源管理
|
||||
services.TryAddSingleton<IVirtualDataSource, VirtualDataSource>();
|
||||
services.TryAddSingleton<IVirtualDataSourceRouteManager, VirtualDataSourceRouteManager>();
|
||||
services.TryAddSingleton<IDataSourceRouteRuleEngine<TShardingDbContext>, DataSourceRouteRuleEngine<TShardingDbContext>>();
|
||||
services.TryAddSingleton<IDataSourceRouteRuleEngineFactory<TShardingDbContext>, DataSourceRouteRuleEngineFactory<TShardingDbContext>>();
|
||||
services.TryAddSingleton<IDataSourceRouteRuleEngine, DataSourceRouteRuleEngine>();
|
||||
services.TryAddSingleton<IDataSourceRouteRuleEngineFactory, DataSourceRouteRuleEngineFactory>();
|
||||
//读写分离链接创建工厂
|
||||
services.TryAddSingleton<IShardingReadWriteAccessor, ShardingReadWriteAccessor>();
|
||||
services.TryAddSingleton<IReadWriteConnectorFactory, ReadWriteConnectorFactory>();
|
||||
|
@ -155,24 +169,33 @@ namespace ShardingCore
|
|||
}
|
||||
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<IQueryCompiler, ShardingQueryCompiler>()
|
||||
.ReplaceService<IDbContextTransactionManager, ShardingRelationalTransactionManager<TShardingDbContext>>()
|
||||
.ReplaceService<IRelationalTransactionFactory, ShardingRelationalTransactionFactory<TShardingDbContext>>();
|
||||
}
|
||||
|
||||
|
||||
private static DbContextOptionsBuilder UseShardingWrapMark(this DbContextOptionsBuilder optionsBuilder,IShardingRuntimeContext shardingRuntimeContext)
|
||||
public static DbContextOptionsBuilder UseShardingOptions(this DbContextOptionsBuilder optionsBuilder,IShardingRuntimeContext shardingRuntimeContext)
|
||||
{
|
||||
var extension = optionsBuilder.CreateOrGetExtension(shardingRuntimeContext);
|
||||
((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension);
|
||||
var shardingOptionsExtension = optionsBuilder.CreateOrGetShardingOptionsExtension(shardingRuntimeContext);
|
||||
((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(shardingOptionsExtension);
|
||||
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>() ??
|
||||
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)
|
||||
{
|
|
@ -67,7 +67,7 @@ namespace ShardingCore
|
|||
shardingRuntimeContext.UseLogfactory(loggerFactory);
|
||||
shardingRuntimeContext.AddServiceConfig(services =>
|
||||
{
|
||||
services.AddSingleton<IDbContextTypeCollector>(sp => new DbContextTypeCollector<TShardingDbContext>());
|
||||
// services.AddSingleton<IDbContextTypeCollector>(sp => new DbContextTypeCollector<TShardingDbContext>());
|
||||
services.AddSingleton<IShardingRouteConfigOptions>(sp => _shardingRouteConfigOptions);
|
||||
|
||||
services.AddSingleton(sp => _shardingConfigOptions);
|
||||
|
|
|
@ -26,7 +26,7 @@ namespace ShardingCore.VirtualRoutes.Abstractions
|
|||
/// 不可以设置一样
|
||||
/// </summary>
|
||||
public virtual string JobName =>
|
||||
$"{EntityMetadata?.ShardingDbContextType?.Name}:{EntityMetadata?.EntityType?.Name}";
|
||||
$"{GetType().Name}:{EntityMetadata?.EntityType?.Name}";
|
||||
|
||||
/// <summary>
|
||||
/// 是否需要自动创建按时间分表的路由
|
||||
|
|
|
@ -14,8 +14,7 @@ namespace ShardingCore.CommonTest
|
|||
private readonly List<string> _allDataSources;
|
||||
public ShardingDataSourceMod()
|
||||
{
|
||||
var entityMetadata = new EntityMetadata(typeof(TestEntity), nameof(TestEntity), typeof(ShardingDataSourceMod),
|
||||
new ReadOnlyCollection<PropertyInfo>(typeof(TestEntity).GetProperties().ToList()), null);
|
||||
var entityMetadata = new EntityMetadata(typeof(TestEntity));
|
||||
var entityMetadataDataSourceBuilder = EntityMetadataDataSourceBuilder<TestEntity>.CreateEntityMetadataDataSourceBuilder(entityMetadata);
|
||||
entityMetadataDataSourceBuilder.ShardingProperty(o => o.Id);
|
||||
entityMetadata.CheckShardingDataSourceMetadata();
|
||||
|
|
|
@ -15,8 +15,7 @@ namespace ShardingCore.CommonTest
|
|||
private readonly List<string> _allTables;
|
||||
public ShardingTableTime()
|
||||
{
|
||||
var entityMetadata = new EntityMetadata(typeof(TestTimeEntity), nameof(TestTimeEntity), typeof(ShardingDataSourceMod),
|
||||
new ReadOnlyCollection<PropertyInfo>(typeof(TestTimeEntity).GetProperties().ToList()), null);
|
||||
var entityMetadata = new EntityMetadata(typeof(TestTimeEntity));
|
||||
var entityMetadataTableBuilder = EntityMetadataTableBuilder<TestTimeEntity>.CreateEntityMetadataTableBuilder(entityMetadata);
|
||||
entityMetadataTableBuilder.ShardingProperty(o => o.Time);
|
||||
entityMetadata.CheckShardingTableMetadata();
|
||||
|
|
Loading…
Reference in New Issue