添加分库sample并且修复若干bug
This commit is contained in:
parent
0b7ef8d6c2
commit
83e74cf5cd
|
@ -35,9 +35,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sample.BulkConsole", "sampl
|
||||||
EndProject
|
EndProject
|
||||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src2x", "src2x", "{F91949B0-02D5-4E3B-ACF4-AFA6C99A1E04}"
|
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src2x", "src2x", "{F91949B0-02D5-4E3B-ACF4-AFA6C99A1E04}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShardingCore.2x", "src2x\ShardingCore.2x\ShardingCore.2x.csproj", "{A07C597D-339D-4378-BE4C-A2AF7473340B}"
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ShardingCore.2x", "src2x\ShardingCore.2x\ShardingCore.2x.csproj", "{A07C597D-339D-4378-BE4C-A2AF7473340B}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShardingCore.Test50_2x", "test\ShardingCore.Test50_2x\ShardingCore.Test50_2x.csproj", "{E4DAA43A-B64D-45CF-81B8-7B8FD338D686}"
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ShardingCore.Test50_2x", "test\ShardingCore.Test50_2x\ShardingCore.Test50_2x.csproj", "{E4DAA43A-B64D-45CF-81B8-7B8FD338D686}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample.SqlServerShardingDataSource", "samples\Sample.SqlServerShardingDataSource\Sample.SqlServerShardingDataSource.csproj", "{0193E3CF-F2FD-449A-B2D5-7F68E551FDBF}"
|
||||||
EndProject
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
|
@ -97,6 +99,10 @@ Global
|
||||||
{E4DAA43A-B64D-45CF-81B8-7B8FD338D686}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{E4DAA43A-B64D-45CF-81B8-7B8FD338D686}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
{E4DAA43A-B64D-45CF-81B8-7B8FD338D686}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
{E4DAA43A-B64D-45CF-81B8-7B8FD338D686}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
{E4DAA43A-B64D-45CF-81B8-7B8FD338D686}.Release|Any CPU.Build.0 = Release|Any CPU
|
{E4DAA43A-B64D-45CF-81B8-7B8FD338D686}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{0193E3CF-F2FD-449A-B2D5-7F68E551FDBF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{0193E3CF-F2FD-449A-B2D5-7F68E551FDBF}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{0193E3CF-F2FD-449A-B2D5-7F68E551FDBF}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{0193E3CF-F2FD-449A-B2D5-7F68E551FDBF}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
|
@ -115,6 +121,7 @@ Global
|
||||||
{2443CC8B-FB7D-47A7-9663-F3848BB30A36} = {EDF8869A-C1E1-491B-BC9F-4A33F4DE1C73}
|
{2443CC8B-FB7D-47A7-9663-F3848BB30A36} = {EDF8869A-C1E1-491B-BC9F-4A33F4DE1C73}
|
||||||
{A07C597D-339D-4378-BE4C-A2AF7473340B} = {F91949B0-02D5-4E3B-ACF4-AFA6C99A1E04}
|
{A07C597D-339D-4378-BE4C-A2AF7473340B} = {F91949B0-02D5-4E3B-ACF4-AFA6C99A1E04}
|
||||||
{E4DAA43A-B64D-45CF-81B8-7B8FD338D686} = {CC2C88C0-65F2-445D-BE78-973B840FE281}
|
{E4DAA43A-B64D-45CF-81B8-7B8FD338D686} = {CC2C88C0-65F2-445D-BE78-973B840FE281}
|
||||||
|
{0193E3CF-F2FD-449A-B2D5-7F68E551FDBF} = {EDF8869A-C1E1-491B-BC9F-4A33F4DE1C73}
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||||
SolutionGuid = {8C07A667-E8B4-43C7-8053-721584BAD291}
|
SolutionGuid = {8C07A667-E8B4-43C7-8053-721584BAD291}
|
||||||
|
|
|
@ -70,11 +70,11 @@ namespace Sample.SqlServer.Controllers
|
||||||
var sresultxasdc = _defaultTableDbContext.Set<SysUserMod>().Where(o => o.Id == "198").ToList();
|
var sresultxasdc = _defaultTableDbContext.Set<SysUserMod>().Where(o => o.Id == "198").ToList();
|
||||||
var sresult = _defaultTableDbContext.Set<SysUserMod>().ToList();
|
var sresult = _defaultTableDbContext.Set<SysUserMod>().ToList();
|
||||||
|
|
||||||
//var sysUserMod98 = result.FirstOrDefault(o => o.Id == "98");
|
var sysUserMod98 = result.FirstOrDefault(o => o.Id == "98");
|
||||||
//_defaultTableDbContext.Attach(sysUserMod98);
|
_defaultTableDbContext.Attach(sysUserMod98);
|
||||||
//sysUserMod98.Name = "name_update" + new Random().Next(1, 99) + "_98";
|
sysUserMod98.Name = "name_update" + new Random().Next(1, 99) + "_98";
|
||||||
//_defaultTableDbContext.Attach(sysUserMod98);
|
_defaultTableDbContext.Attach(sysUserMod98);
|
||||||
//await _defaultTableDbContext.SaveChangesAsync();
|
await _defaultTableDbContext.SaveChangesAsync();
|
||||||
var stu = new STU() { Id = "198" };
|
var stu = new STU() { Id = "198" };
|
||||||
var sresultx111x = _defaultTableDbContext.Set<SysUserMod>().FirstOrDefault(o => o.Id == stu.Id);
|
var sresultx111x = _defaultTableDbContext.Set<SysUserMod>().FirstOrDefault(o => o.Id == stu.Id);
|
||||||
|
|
||||||
|
@ -87,8 +87,8 @@ namespace Sample.SqlServer.Controllers
|
||||||
|
|
||||||
var mod00s = await _defaultTableDbContext.Set<SysUserMod>().Skip(10).Take(11).ToListAsync();
|
var mod00s = await _defaultTableDbContext.Set<SysUserMod>().Skip(10).Take(11).ToListAsync();
|
||||||
}
|
}
|
||||||
_defaultTableDbContext.RemoveRange(_defaultTableDbContext.Set<SysUserMod>());
|
//_defaultTableDbContext.RemoveRange(_defaultTableDbContext.Set<SysUserMod>());
|
||||||
await _defaultTableDbContext.SaveChangesAsync();
|
//await _defaultTableDbContext.SaveChangesAsync();
|
||||||
return Ok();
|
return Ok();
|
||||||
}
|
}
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
|
|
|
@ -0,0 +1,67 @@
|
||||||
|
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.SqlServerShardingDataSource.DbContexts;
|
||||||
|
using Sample.SqlServerShardingDataSource.Domain.Entities;
|
||||||
|
|
||||||
|
namespace Sample.SqlServerShardingDataSource.Controllers
|
||||||
|
{
|
||||||
|
[ApiController]
|
||||||
|
[Route("[controller]")]
|
||||||
|
public class WeatherForecastController : ControllerBase
|
||||||
|
{
|
||||||
|
private static readonly string[] Summaries = new[]
|
||||||
|
{
|
||||||
|
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
|
||||||
|
};
|
||||||
|
|
||||||
|
private readonly ILogger<WeatherForecastController> _logger;
|
||||||
|
private readonly DefaultShardingDbContext _defaultShardingDbContext;
|
||||||
|
|
||||||
|
public WeatherForecastController(ILogger<WeatherForecastController> logger, DefaultShardingDbContext defaultShardingDbContext)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
_defaultShardingDbContext = defaultShardingDbContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet]
|
||||||
|
public async Task<IEnumerable<WeatherForecast>> Get()
|
||||||
|
{
|
||||||
|
var resultx112331 = await _defaultShardingDbContext.Set<SysUserMod>().CountAsync();
|
||||||
|
var resultx11233411 = _defaultShardingDbContext.Set<SysUserMod>().Count();
|
||||||
|
var resultx11231 = await _defaultShardingDbContext.Set<SysUserMod>().Where(o => o.Age == 198198).Select(o => o.Id).ContainsAsync("1981");
|
||||||
|
var resultx1121 = await _defaultShardingDbContext.Set<SysUserMod>().Where(o => o.Id == "198").SumAsync(o => o.Age);
|
||||||
|
var resultx111 = await _defaultShardingDbContext.Set<SysUserMod>().FirstOrDefaultAsync(o => o.Id == "198");
|
||||||
|
var resultx2 = await _defaultShardingDbContext.Set<SysUserMod>().CountAsync(o => o.Age <= 10);
|
||||||
|
var resultx = await _defaultShardingDbContext.Set<SysUserMod>().Where(o => o.Id == "198").FirstOrDefaultAsync();
|
||||||
|
var resultx33 = await _defaultShardingDbContext.Set<SysUserMod>().Where(o => o.Id == "198").Select(o => o.Id).FirstOrDefaultAsync();
|
||||||
|
var resulxxt = await _defaultShardingDbContext.Set<SysUserMod>().Where(o => o.Id == "198").ToListAsync();
|
||||||
|
var result = await _defaultShardingDbContext.Set<SysUserMod>().ToListAsync();
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var sresultx11231 = _defaultShardingDbContext.Set<SysUserMod>().Where(o => o.Age == 198198).Select(o => o.Id).Contains("1981");
|
||||||
|
var sresultx1121 = _defaultShardingDbContext.Set<SysUserMod>().Where(o => o.Id == "198").Sum(o => o.Age);
|
||||||
|
var sresultx111 = _defaultShardingDbContext.Set<SysUserMod>().FirstOrDefault(o => o.Id == "198");
|
||||||
|
var sresultx2 = _defaultShardingDbContext.Set<SysUserMod>().Count(o => o.Age <= 10);
|
||||||
|
var sresultx = _defaultShardingDbContext.Set<SysUserMod>().Where(o => o.Id == "198").FirstOrDefault();
|
||||||
|
var sresultx33 = _defaultShardingDbContext.Set<SysUserMod>().Where(o => o.Id == "198").Select(o => o.Id).FirstOrDefault();
|
||||||
|
var sresultxc = _defaultShardingDbContext.Set<SysUserMod>().Where(o => o.Id == "198").Select(o => o.Id).ToList();
|
||||||
|
var sresultxasdc = _defaultShardingDbContext.Set<SysUserMod>().Where(o => o.Id == "198").ToList();
|
||||||
|
var sresult = _defaultShardingDbContext.Set<SysUserMod>().ToList();
|
||||||
|
var rng = new Random();
|
||||||
|
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
|
||||||
|
{
|
||||||
|
Date = DateTime.Now.AddDays(index),
|
||||||
|
TemperatureC = rng.Next(-20, 55),
|
||||||
|
Summary = Summaries[rng.Next(Summaries.Length)]
|
||||||
|
})
|
||||||
|
.ToArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,54 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Sample.SqlServerShardingDataSource.DbContexts;
|
||||||
|
using Sample.SqlServerShardingDataSource.Domain.Entities;
|
||||||
|
using ShardingCore;
|
||||||
|
|
||||||
|
namespace Sample.SqlServerShardingDataSource
|
||||||
|
{
|
||||||
|
/*
|
||||||
|
* @Author: xjm
|
||||||
|
* @Description:
|
||||||
|
* @Date: Tuesday, 26 January 2021 12:29:04
|
||||||
|
* @Email: 326308290@qq.com
|
||||||
|
*/
|
||||||
|
public static class DIExtension
|
||||||
|
{
|
||||||
|
public static IApplicationBuilder UseShardingCore(this IApplicationBuilder app)
|
||||||
|
{
|
||||||
|
var shardingBootstrapper = app.ApplicationServices.GetRequiredService<IShardingBootstrapper>();
|
||||||
|
shardingBootstrapper.Start();
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void DbSeed(this IApplicationBuilder app)
|
||||||
|
{
|
||||||
|
using (var scope = app.ApplicationServices.CreateScope())
|
||||||
|
{
|
||||||
|
var virtualDbContext = scope.ServiceProvider.GetService<DefaultShardingDbContext>();
|
||||||
|
if (!virtualDbContext.Set<SysUserMod>().Any())
|
||||||
|
{
|
||||||
|
var ids = Enumerable.Range(1, 1000);
|
||||||
|
var userMods = new List<SysUserMod>();
|
||||||
|
foreach (var id in ids)
|
||||||
|
{
|
||||||
|
userMods.Add(new SysUserMod()
|
||||||
|
{
|
||||||
|
Id = id.ToString(),
|
||||||
|
Age = id,
|
||||||
|
Name = $"name_{id}",
|
||||||
|
AgeGroup = Math.Abs(id % 10)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
virtualDbContext.AddRange(userMods);
|
||||||
|
|
||||||
|
virtualDbContext.SaveChanges();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,23 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Sample.SqlServerShardingDataSource.Domain.Maps;
|
||||||
|
|
||||||
|
namespace Sample.SqlServerShardingDataSource.DbContexts
|
||||||
|
{
|
||||||
|
public class DefaultDbContext: DbContext
|
||||||
|
{
|
||||||
|
public DefaultDbContext(DbContextOptions<DefaultDbContext> options) : base(options)
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
base.OnModelCreating(modelBuilder);
|
||||||
|
modelBuilder.ApplyConfiguration(new SysUserModMap());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,24 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Sample.SqlServerShardingDataSource.Domain.Maps;
|
||||||
|
using ShardingCore.Sharding;
|
||||||
|
|
||||||
|
namespace Sample.SqlServerShardingDataSource.DbContexts
|
||||||
|
{
|
||||||
|
public class DefaultShardingDbContext:AbstractShardingDbContext<DefaultDbContext>
|
||||||
|
{
|
||||||
|
public DefaultShardingDbContext(DbContextOptions options) : base(options)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
base.OnModelCreating(modelBuilder);
|
||||||
|
modelBuilder.ApplyConfiguration(new SysUserModMap());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,31 @@
|
||||||
|
using ShardingCore.Core;
|
||||||
|
|
||||||
|
namespace Sample.SqlServerShardingDataSource.Domain.Entities
|
||||||
|
{
|
||||||
|
/*
|
||||||
|
* @Author: xjm
|
||||||
|
* @Description:
|
||||||
|
* @Date: Tuesday, 26 January 2021 12:25:39
|
||||||
|
* @Email: 326308290@qq.com
|
||||||
|
*/
|
||||||
|
/// <summary>
|
||||||
|
/// 用户表
|
||||||
|
/// </summary>
|
||||||
|
public class SysUserMod : IShardingDataSource
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 用户Id用于分表
|
||||||
|
/// </summary>
|
||||||
|
[ShardingDataSourceKey]
|
||||||
|
public string Id { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// 用户名称
|
||||||
|
/// </summary>
|
||||||
|
public string Name { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// 用户姓名
|
||||||
|
/// </summary>
|
||||||
|
public int Age { get; set; }
|
||||||
|
public int AgeGroup { get; set; }
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,23 @@
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||||
|
using Sample.SqlServerShardingDataSource.Domain.Entities;
|
||||||
|
|
||||||
|
namespace Sample.SqlServerShardingDataSource.Domain.Maps
|
||||||
|
{
|
||||||
|
/*
|
||||||
|
* @Author: xjm
|
||||||
|
* @Description:
|
||||||
|
* @Date: Thursday, 14 January 2021 15:37:33
|
||||||
|
* @Email: 326308290@qq.com
|
||||||
|
*/
|
||||||
|
public class SysUserModMap:IEntityTypeConfiguration<SysUserMod>
|
||||||
|
{
|
||||||
|
public void Configure(EntityTypeBuilder<SysUserMod> builder)
|
||||||
|
{
|
||||||
|
builder.HasKey(o => o.Id);
|
||||||
|
builder.Property(o => o.Id).IsRequired().HasMaxLength(128);
|
||||||
|
builder.Property(o => o.Name).HasMaxLength(128);
|
||||||
|
builder.ToTable(nameof(SysUserMod));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,26 @@
|
||||||
|
using Microsoft.AspNetCore.Hosting;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace Sample.SqlServerShardingDataSource
|
||||||
|
{
|
||||||
|
public class Program
|
||||||
|
{
|
||||||
|
public static void Main(string[] args)
|
||||||
|
{
|
||||||
|
CreateHostBuilder(args).Build().Run();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IHostBuilder CreateHostBuilder(string[] args) =>
|
||||||
|
Host.CreateDefaultBuilder(args)
|
||||||
|
.ConfigureWebHostDefaults(webBuilder =>
|
||||||
|
{
|
||||||
|
webBuilder.UseStartup<Startup>();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,31 @@
|
||||||
|
{
|
||||||
|
"$schema": "http://json.schemastore.org/launchsettings.json",
|
||||||
|
"iisSettings": {
|
||||||
|
"windowsAuthentication": false,
|
||||||
|
"anonymousAuthentication": true,
|
||||||
|
"iisExpress": {
|
||||||
|
"applicationUrl": "http://localhost:6564",
|
||||||
|
"sslPort": 0
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"profiles": {
|
||||||
|
"IIS Express": {
|
||||||
|
"commandName": "IISExpress",
|
||||||
|
"launchBrowser": true,
|
||||||
|
"launchUrl": "weatherforecast",
|
||||||
|
"environmentVariables": {
|
||||||
|
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Sample.SqlServerShardingDataSource": {
|
||||||
|
"commandName": "Project",
|
||||||
|
"dotnetRunMessages": "true",
|
||||||
|
"launchBrowser": true,
|
||||||
|
"launchUrl": "weatherforecast",
|
||||||
|
"applicationUrl": "http://localhost:5000",
|
||||||
|
"environmentVariables": {
|
||||||
|
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,15 @@
|
||||||
|
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net5.0</TargetFramework>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.10" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\..\src\ShardingCore\ShardingCore.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
|
@ -0,0 +1,59 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Linq.Expressions;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Sample.SqlServerShardingDataSource.Domain.Entities;
|
||||||
|
using ShardingCore.Core.VirtualRoutes;
|
||||||
|
using ShardingCore.Core.VirtualRoutes.DataSourceRoutes.Abstractions;
|
||||||
|
using ShardingCore.Helpers;
|
||||||
|
|
||||||
|
namespace Sample.SqlServerShardingDataSource.Shardings
|
||||||
|
{
|
||||||
|
public class SysUserModVirtualDataSourceRoute:AbstractShardingOperatorVirtualDataSourceRoute<SysUserMod,string>
|
||||||
|
{
|
||||||
|
protected readonly int Mod=3;
|
||||||
|
protected readonly int TailLength=1;
|
||||||
|
protected readonly char PaddingChar='0';
|
||||||
|
|
||||||
|
protected override string ConvertToShardingKey(object shardingKey)
|
||||||
|
{
|
||||||
|
return shardingKey.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override string ShardingKeyToDataSourceName(object shardingKey)
|
||||||
|
{
|
||||||
|
var shardingKeyStr = ConvertToShardingKey(shardingKey);
|
||||||
|
return "ds"+Math.Abs(ShardingCoreHelper.GetStringHashCode(shardingKeyStr) % Mod).ToString().PadLeft(TailLength, PaddingChar); ;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override List<string> GetAllDataSourceNames()
|
||||||
|
{
|
||||||
|
return new List<string>()
|
||||||
|
{
|
||||||
|
"ds0",
|
||||||
|
"ds1",
|
||||||
|
"ds2"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool AddDataSourceName(string dataSourceName)
|
||||||
|
{
|
||||||
|
throw new NotImplementedException();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override Expression<Func<string, bool>> GetRouteToFilter(string shardingKey, ShardingOperatorEnum shardingOperator)
|
||||||
|
{
|
||||||
|
|
||||||
|
var t = ShardingKeyToDataSourceName(shardingKey);
|
||||||
|
switch (shardingOperator)
|
||||||
|
{
|
||||||
|
case ShardingOperatorEnum.Equal: return tail => tail == t;
|
||||||
|
default:
|
||||||
|
{
|
||||||
|
return tail => true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,82 @@
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Microsoft.AspNetCore.Hosting;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Sample.SqlServerShardingDataSource.DbContexts;
|
||||||
|
using Sample.SqlServerShardingDataSource.Shardings;
|
||||||
|
using ShardingCore;
|
||||||
|
|
||||||
|
namespace Sample.SqlServerShardingDataSource
|
||||||
|
{
|
||||||
|
public class Startup
|
||||||
|
{
|
||||||
|
public static readonly ILoggerFactory efLogger = LoggerFactory.Create(builder =>
|
||||||
|
{
|
||||||
|
builder.AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information).AddConsole();
|
||||||
|
});
|
||||||
|
public Startup(IConfiguration configuration)
|
||||||
|
{
|
||||||
|
Configuration = configuration;
|
||||||
|
}
|
||||||
|
|
||||||
|
public IConfiguration Configuration { get; }
|
||||||
|
|
||||||
|
// This method gets called by the runtime. Use this method to add services to the container.
|
||||||
|
public void ConfigureServices(IServiceCollection services)
|
||||||
|
{
|
||||||
|
|
||||||
|
services.AddControllers();
|
||||||
|
|
||||||
|
|
||||||
|
services.AddShardingDbContext<DefaultShardingDbContext, DefaultDbContext>(
|
||||||
|
o =>
|
||||||
|
o.UseSqlServer("Data Source=localhost;Initial Catalog=ShardingCoreDBxx0;Integrated Security=True;")
|
||||||
|
).Begin(true, true)
|
||||||
|
.AddShardingQuery((conStr, builder) => builder.UseSqlServer(conStr).UseLoggerFactory(efLogger)
|
||||||
|
.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking))
|
||||||
|
.AddShardingTransaction((connection, builder) =>
|
||||||
|
builder.UseSqlServer(connection).UseLoggerFactory(efLogger))
|
||||||
|
.AddDefaultDataSource("ds0",
|
||||||
|
"Data Source=localhost;Initial Catalog=ShardingCoreDBxx0;Integrated Security=True;")
|
||||||
|
.AddShardingDataBase(sp =>
|
||||||
|
{
|
||||||
|
return new Dictionary<string, string>()
|
||||||
|
{
|
||||||
|
{"ds1", "Data Source=localhost;Initial Catalog=ShardingCoreDBxx1;Integrated Security=True;"},
|
||||||
|
{"ds2", "Data Source=localhost;Initial Catalog=ShardingCoreDBxx2;Integrated Security=True;"},
|
||||||
|
};
|
||||||
|
}, o =>
|
||||||
|
{
|
||||||
|
o.AddShardingDatabaseRoute<SysUserModVirtualDataSourceRoute>();
|
||||||
|
}).End();
|
||||||
|
}
|
||||||
|
|
||||||
|
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
|
||||||
|
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
|
||||||
|
{
|
||||||
|
if (env.IsDevelopment())
|
||||||
|
{
|
||||||
|
app.UseDeveloperExceptionPage();
|
||||||
|
}
|
||||||
|
|
||||||
|
app.UseShardingCore();
|
||||||
|
app.UseRouting();
|
||||||
|
|
||||||
|
app.UseAuthorization();
|
||||||
|
|
||||||
|
app.UseEndpoints(endpoints =>
|
||||||
|
{
|
||||||
|
endpoints.MapControllers();
|
||||||
|
});
|
||||||
|
app.DbSeed();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,15 @@
|
||||||
|
using System;
|
||||||
|
|
||||||
|
namespace Sample.SqlServerShardingDataSource
|
||||||
|
{
|
||||||
|
public class WeatherForecast
|
||||||
|
{
|
||||||
|
public DateTime Date { get; set; }
|
||||||
|
|
||||||
|
public int TemperatureC { get; set; }
|
||||||
|
|
||||||
|
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
|
||||||
|
|
||||||
|
public string Summary { get; set; }
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,9 @@
|
||||||
|
{
|
||||||
|
"Logging": {
|
||||||
|
"LogLevel": {
|
||||||
|
"Default": "Information",
|
||||||
|
"Microsoft": "Warning",
|
||||||
|
"Microsoft.Hosting.Lifetime": "Information"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,10 @@
|
||||||
|
{
|
||||||
|
"Logging": {
|
||||||
|
"LogLevel": {
|
||||||
|
"Default": "Information",
|
||||||
|
"Microsoft": "Warning",
|
||||||
|
"Microsoft.Hosting.Lifetime": "Information"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"AllowedHosts": "*"
|
||||||
|
}
|
|
@ -13,8 +13,11 @@ namespace ShardingCore.Core.VirtualRoutes.DataSourceRoutes.Abstractions
|
||||||
*/
|
*/
|
||||||
public abstract class AbstractVirtualDataSourceRoute<T, TKey> : IVirtualDataSourceRoute<T> where T : class, IShardingDataSource
|
public abstract class AbstractVirtualDataSourceRoute<T, TKey> : IVirtualDataSourceRoute<T> where T : class, IShardingDataSource
|
||||||
{
|
{
|
||||||
|
private bool _inited = false;
|
||||||
public void Init()
|
public void Init()
|
||||||
{
|
{
|
||||||
|
if (_inited)
|
||||||
|
throw new InvalidOperationException("already init");
|
||||||
var paginationConfiguration = CreatePaginationConfiguration();
|
var paginationConfiguration = CreatePaginationConfiguration();
|
||||||
if (paginationConfiguration != null)
|
if (paginationConfiguration != null)
|
||||||
{
|
{
|
||||||
|
@ -22,6 +25,8 @@ namespace ShardingCore.Core.VirtualRoutes.DataSourceRoutes.Abstractions
|
||||||
var paginationBuilder = new PaginationBuilder<T>(PaginationMetadata);
|
var paginationBuilder = new PaginationBuilder<T>(PaginationMetadata);
|
||||||
paginationConfiguration.Configure(paginationBuilder);
|
paginationConfiguration.Configure(paginationBuilder);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_inited = true;
|
||||||
}
|
}
|
||||||
public virtual IPaginationConfiguration<T> CreatePaginationConfiguration()
|
public virtual IPaginationConfiguration<T> CreatePaginationConfiguration()
|
||||||
{
|
{
|
||||||
|
|
|
@ -42,7 +42,7 @@ namespace ShardingCore
|
||||||
Action<DbContextOptionsBuilder> optionsAction = null,
|
Action<DbContextOptionsBuilder> optionsAction = null,
|
||||||
ServiceLifetime contextLifetime = ServiceLifetime.Scoped,
|
ServiceLifetime contextLifetime = ServiceLifetime.Scoped,
|
||||||
ServiceLifetime optionsLifetime = ServiceLifetime.Scoped)
|
ServiceLifetime optionsLifetime = ServiceLifetime.Scoped)
|
||||||
where TActualDbContext : DbContext, IShardingTableDbContext
|
where TActualDbContext : DbContext
|
||||||
where TShardingDbContext : DbContext, IShardingDbContext<TActualDbContext>
|
where TShardingDbContext : DbContext, IShardingDbContext<TActualDbContext>
|
||||||
{
|
{
|
||||||
|
|
||||||
|
|
|
@ -26,7 +26,7 @@ namespace ShardingCore.Extensions
|
||||||
if (!entity.IsShardingDataSource())
|
if (!entity.IsShardingDataSource())
|
||||||
return virtualDataSource.DefaultDataSourceName;
|
return virtualDataSource.DefaultDataSourceName;
|
||||||
|
|
||||||
return virtualDataSource.RouteTo(typeof(TEntity),
|
return virtualDataSource.RouteTo(entity.GetType(),
|
||||||
new ShardingDataSourceRouteConfig(shardingDataSource: entity as IShardingDataSource))[0];
|
new ShardingDataSourceRouteConfig(shardingDataSource: entity as IShardingDataSource))[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -33,7 +33,7 @@ namespace ShardingCore
|
||||||
void Initialize();
|
void Initialize();
|
||||||
}
|
}
|
||||||
|
|
||||||
public class ShardingDbContextBootstrapper<TShardingDbContext>: IShardingDbContextBootstrapper where TShardingDbContext:DbContext,IShardingDbContext
|
public class ShardingDbContextBootstrapper<TShardingDbContext> : IShardingDbContextBootstrapper where TShardingDbContext : DbContext, IShardingDbContext
|
||||||
{
|
{
|
||||||
private readonly IShardingConfigOption _shardingConfigOption;
|
private readonly IShardingConfigOption _shardingConfigOption;
|
||||||
private readonly IRouteTailFactory _routeTailFactory;
|
private readonly IRouteTailFactory _routeTailFactory;
|
||||||
|
@ -46,22 +46,23 @@ namespace ShardingCore
|
||||||
_shardingConfigOption = shardingConfigOption;
|
_shardingConfigOption = shardingConfigOption;
|
||||||
_routeTailFactory = ShardingContainer.GetService<IRouteTailFactory>();
|
_routeTailFactory = ShardingContainer.GetService<IRouteTailFactory>();
|
||||||
_virtualTableManager = ShardingContainer.GetService<IVirtualTableManager<TShardingDbContext>>();
|
_virtualTableManager = ShardingContainer.GetService<IVirtualTableManager<TShardingDbContext>>();
|
||||||
_tableCreator=ShardingContainer.GetService<IShardingTableCreator<TShardingDbContext>>();
|
_tableCreator = ShardingContainer.GetService<IShardingTableCreator<TShardingDbContext>>();
|
||||||
_logger = ShardingContainer.GetService<ILogger<ShardingDbContextBootstrapper<TShardingDbContext>>>();
|
_logger = ShardingContainer.GetService<ILogger<ShardingDbContextBootstrapper<TShardingDbContext>>>();
|
||||||
}
|
}
|
||||||
public void Initialize()
|
public void Initialize()
|
||||||
{
|
{
|
||||||
var virtualDataSource = ShardingContainer.GetService<IVirtualDataSource<TShardingDbContext>>();
|
var virtualDataSource = ShardingContainer.GetService<IVirtualDataSource<TShardingDbContext>>();
|
||||||
using (var serviceScope = ShardingContainer.Services.CreateScope())
|
var dataSources = _shardingConfigOption.GetDataSources();
|
||||||
|
virtualDataSource.AddPhysicDataSource(new DefaultPhysicDataSource(_shardingConfigOption.DefaultDataSourceName, _shardingConfigOption.DefaultConnectionString, true));
|
||||||
|
//foreach (var dataSourceKv in dataSources)
|
||||||
|
//{
|
||||||
|
// virtualDataSource.AddPhysicDataSource(new DefaultPhysicDataSource(dataSourceKv.Key,
|
||||||
|
// dataSourceKv.Value, false));
|
||||||
|
//}
|
||||||
|
foreach (var dataSourceKv in dataSources)
|
||||||
{
|
{
|
||||||
var dataSources = _shardingConfigOption.GetDataSources();
|
|
||||||
virtualDataSource.AddPhysicDataSource(new DefaultPhysicDataSource(_shardingConfigOption.DefaultDataSourceName, _shardingConfigOption.DefaultConnectionString,true));
|
using (var serviceScope = ShardingContainer.Services.CreateScope())
|
||||||
//foreach (var dataSourceKv in dataSources)
|
|
||||||
//{
|
|
||||||
// virtualDataSource.AddPhysicDataSource(new DefaultPhysicDataSource(dataSourceKv.Key,
|
|
||||||
// dataSourceKv.Value, false));
|
|
||||||
//}
|
|
||||||
foreach (var dataSourceKv in dataSources)
|
|
||||||
{
|
{
|
||||||
var dataSourceName = dataSourceKv.Key;
|
var dataSourceName = dataSourceKv.Key;
|
||||||
var connectionString = dataSourceKv.Value;
|
var connectionString = dataSourceKv.Value;
|
||||||
|
@ -95,17 +96,17 @@ namespace ShardingCore
|
||||||
#endif
|
#endif
|
||||||
virtualTable.SetVirtualTableName(tableName);
|
virtualTable.SetVirtualTableName(tableName);
|
||||||
_virtualTableManager.AddVirtualTable(virtualTable);
|
_virtualTableManager.AddVirtualTable(virtualTable);
|
||||||
CreateDataTable(dataSourceName,virtualTable);
|
CreateDataTable(dataSourceName, virtualTable);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
private void EnsureCreated(DbContext context,string dataSourceName)
|
private void EnsureCreated(DbContext context, string dataSourceName)
|
||||||
{
|
{
|
||||||
if (context is IShardingDbContext shardingDbContext)
|
if (context is IShardingDbContext shardingDbContext)
|
||||||
{
|
{
|
||||||
var dbContext = shardingDbContext.GetDbContext(dataSourceName,false, _routeTailFactory.Create(string.Empty));
|
var dbContext = shardingDbContext.GetDbContext(dataSourceName, false, _routeTailFactory.Create(string.Empty));
|
||||||
var modelCacheSyncObject = dbContext.GetModelCacheSyncObject();
|
var modelCacheSyncObject = dbContext.GetModelCacheSyncObject();
|
||||||
|
|
||||||
lock (modelCacheSyncObject)
|
lock (modelCacheSyncObject)
|
||||||
|
@ -190,7 +191,7 @@ namespace ShardingCore
|
||||||
|
|
||||||
return _shardingConfigOption.CreateShardingTableOnStart.GetValueOrDefault();
|
return _shardingConfigOption.CreateShardingTableOnStart.GetValueOrDefault();
|
||||||
}
|
}
|
||||||
private void CreateDataTable(string dataSourceName,IVirtualTable virtualTable)
|
private void CreateDataTable(string dataSourceName, IVirtualTable virtualTable)
|
||||||
{
|
{
|
||||||
var shardingConfig = virtualTable.ShardingConfig;
|
var shardingConfig = virtualTable.ShardingConfig;
|
||||||
foreach (var tail in virtualTable.GetVirtualRoute().GetAllTails())
|
foreach (var tail in virtualTable.GetVirtualRoute().GetAllTails())
|
||||||
|
@ -201,7 +202,7 @@ namespace ShardingCore
|
||||||
{
|
{
|
||||||
//添加物理表
|
//添加物理表
|
||||||
virtualTable.AddPhysicTable(new DefaultPhysicTable(virtualTable, tail));
|
virtualTable.AddPhysicTable(new DefaultPhysicTable(virtualTable, tail));
|
||||||
_tableCreator.CreateTable(dataSourceName,virtualTable.EntityType, tail);
|
_tableCreator.CreateTable(dataSourceName, virtualTable.EntityType, tail);
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
|
|
|
@ -50,7 +50,7 @@ namespace ShardingCore.VirtualRoutes.Mods
|
||||||
public override string ShardingKeyToTail(object shardingKey)
|
public override string ShardingKeyToTail(object shardingKey)
|
||||||
{
|
{
|
||||||
var shardingKeyStr = ConvertToShardingKey(shardingKey);
|
var shardingKeyStr = ConvertToShardingKey(shardingKey);
|
||||||
return Math.Abs(ShardingCoreHelper.GetStringHashCode(shardingKeyStr) % Mod).ToString().PadLeft(TailLength,PaddingChar);;
|
return Math.Abs(ShardingCoreHelper.GetStringHashCode(shardingKeyStr) % Mod).ToString().PadLeft(TailLength,PaddingChar);
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 将shardingKey转成对应的字符串
|
/// 将shardingKey转成对应的字符串
|
||||||
|
|
Loading…
Reference in New Issue