完善demo,mysql多dbcontext下的使用

This commit is contained in:
xuejiaming 2022-07-20 22:15:05 +08:00
parent 09c64cc328
commit 14489a020c
6 changed files with 80 additions and 43 deletions

View File

@ -9,6 +9,7 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Sample.MySql.DbContexts;
using Sample.MySql.Domain.Entities;
using Sample.MySql.multi;
using ShardingCore.Extensions.ShardingQueryableExtensions;
using ShardingCore.TableCreator;
@ -20,10 +21,12 @@ namespace Sample.MySql.Controllers
{
private readonly DefaultShardingDbContext _defaultTableDbContext;
private readonly OtherDbContext _otherDbContext;
public WeatherForecastController(DefaultShardingDbContext defaultTableDbContext)
public WeatherForecastController(DefaultShardingDbContext defaultTableDbContext,OtherDbContext otherDbContext)
{
_defaultTableDbContext = defaultTableDbContext;
_otherDbContext = otherDbContext;
}
[HttpGet]
@ -43,6 +46,7 @@ namespace Sample.MySql.Controllers
var shardingFirstOrDefaultAsync = await _defaultTableDbContext.Set<SysUserLogByMonth>().ToListAsync();
var shardingCountAsync = await _defaultTableDbContext.Set<SysUserMod>().CountAsync();
var shardingCountAsyn2c = _defaultTableDbContext.Set<SysUserLogByMonth>().Count();
var count = _otherDbContext.Set<MyUser>().Count();
// var dbConnection = _defaultTableDbContext.Database.GetDbConnection();
// if (dbConnection.State != ConnectionState.Open)
// {
@ -62,29 +66,17 @@ namespace Sample.MySql.Controllers
return Ok(1);
}
// [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();
// }
[HttpGet]
public async Task<IActionResult> Get1()
{
var resultX = await _defaultTableDbContext.Set<SysUserMod>()
.Where(o => o.Id == "2" || o.Id == "3").FirstOrDefaultAsync();
Console.WriteLine("-----------------------------------------------------------------------------------------------------");
var resultY = await _defaultTableDbContext.Set<SysUserMod>().FirstOrDefaultAsync(o => o.Id == "2" || o.Id == "3");
Console.WriteLine("-----------------------------------------------------------------------------------------------------");
var result = await _defaultTableDbContext.Set<SysTest>().AnyAsync();
Console.WriteLine("-----------------------------------------------------------------------------------------------------");
return Ok();
}
}
}

View File

@ -1,5 +1,9 @@
using System;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Sample.MySql.Domain.Entities;
using Sample.MySql.Domain.Maps;
using ShardingCore.Core.VirtualRoutes.TableRoutes.RouteTails.Abstractions;
using ShardingCore.Sharding;
@ -15,6 +19,8 @@ namespace Sample.MySql.DbContexts
//ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
//Database.SetCommandTimeout(30000);
}
private readonly MethodInfo? _configureGlobalFiltersMethodInfo =
typeof(DefaultShardingDbContext).GetMethod(nameof(ConfigureGlobalFilters), BindingFlags.Instance | BindingFlags.NonPublic);
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
@ -22,8 +28,37 @@ namespace Sample.MySql.DbContexts
modelBuilder.ApplyConfiguration(new SysUserModMap());
modelBuilder.ApplyConfiguration(new SysTestMap());
modelBuilder.ApplyConfiguration(new SysUserLogByMonthMap());
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
_configureGlobalFiltersMethodInfo?.MakeGenericMethod(entityType.ClrType)
.Invoke(this, new object[] { modelBuilder, entityType });
}
}
protected void ConfigureGlobalFilters<TEntity>(ModelBuilder modelBuilder, IMutableEntityType entityType)
where TEntity : class
{
var filterExpression = CreateFilterExpression<TEntity>();
if (filterExpression != null) modelBuilder.Entity<TEntity>().HasQueryFilter(filterExpression);
}
protected Expression<Func<TEntity, bool>>? CreateFilterExpression<TEntity>() where TEntity : class
{
Expression<Func<TEntity, bool>>? expression = null;
if (typeof(TEntity) == typeof(SysTest))
{
expression = e => ((IUser)e).UserId == "123";
} if (typeof(TEntity) == typeof(SysUserMod))
{
expression = e => ((IAge)e).Age == 99;
}
return expression;
}
public IRouteTail RouteTail { get; set; }
}
}

View File

@ -1,6 +1,10 @@
namespace Sample.MySql.Domain.Entities
{
public class SysTest
public interface IUser
{
string UserId { get; set; }
}
public class SysTest:IUser
{
public string Id { get; set; }
public string UserId { get; set; }

View File

@ -8,7 +8,11 @@ namespace Sample.MySql.Domain.Entities
* @Date: Tuesday, 26 January 2021 12:25:39
* @Email: 326308290@qq.com
*/
public class SysUserMod
public interface IAge
{
int Age { get; set; }
}
public class SysUserMod:IAge
{
/// <summary>
/// 用户Id用于分表

View File

@ -123,25 +123,25 @@ namespace Sample.MySql
{ "ds1", "server=127.0.0.1;port=3306;database=dbdbd1;userid=root;password=root;" },
{ "ds2", "server=127.0.0.1;port=3306;database=dbdbd2;userid=root;password=root;" }
});
o.AddReadWriteSeparation(sp =>
{
return new Dictionary<string, IEnumerable<string>>()
{
{
"ds0",
new[]
{
"server=127.0.0.1;port=3306;database=dbdbd0_0;userid=root;password=root;"
}
}
};
}, defaultEnable: true, readStrategyEnum: ReadStrategyEnum.Loop,
readConnStringGetStrategy: ReadConnStringGetStrategyEnum.LatestEveryTime);
// o.AddReadWriteSeparation(sp =>
// {
// return new Dictionary<string, IEnumerable<string>>()
// {
// {
// "ds0",
// new[]
// {
// "server=127.0.0.1;port=3306;database=dbdbd0_0;userid=root;password=root;"
// }
// }
// };
// }, defaultEnable: true, readStrategyEnum: ReadStrategyEnum.Loop,
// readConnStringGetStrategy: ReadConnStringGetStrategyEnum.LatestEveryTime);
o.UseShardingMigrationConfigure(b =>
{
b.ReplaceService<IMigrationsSqlGenerator, ShardingMySqlMigrationsSqlGenerator>();
});
})//.ReplaceService<ITableEnsureManager, MySqlTableEnsureManager>(ServiceLifetime.Singleton)
}).ReplaceService<ITableEnsureManager, MySqlTableEnsureManager>(ServiceLifetime.Singleton)
.Build(sp);
stopwatch.Stop();
Console.WriteLine("ShardingRuntimeContext build:" + stopwatch.ElapsedMilliseconds);

View File

@ -29,7 +29,7 @@ namespace ShardingCore.Bootstrappers
{
private readonly IShardingProvider _shardingProvider;
private readonly IDbContextCreator _dbContextCreator;
private readonly DoOnlyOnce _onlyOnce=new DoOnlyOnce();
public ShardingBootstrapper(IShardingProvider shardingProvider,IDbContextCreator dbContextCreator)
{
_shardingProvider = shardingProvider;
@ -37,6 +37,8 @@ namespace ShardingCore.Bootstrappers
}
public void AutoShardingCreate()
{
if (!_onlyOnce.IsUnDo())
return;
CheckRequirement();
StartAutoShardingJob();
}