添加自动建表的例子

This commit is contained in:
xuejmnet 2021-02-02 17:37:41 +08:00
parent af02282080
commit 6441b5e475
19 changed files with 374 additions and 6 deletions

View File

@ -34,6 +34,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShardingCore.MySql.2x", "sr
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShardingCore.Test50.MySql", "test\ShardingCore.Test50.MySql\ShardingCore.Test50.MySql.csproj", "{C8FAB96F-F13E-4094-883C-2D38D39EE4A3}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Samples.AutoByDate.SqlServer", "samples\Samples.AutoByDate.SqlServer\Samples.AutoByDate.SqlServer.csproj", "{C34FCF48-1A98-4268-BFEE-6C9BFC7FD539}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -52,6 +54,7 @@ Global
{954C4CA2-9CF4-4C2C-8DE6-180DD8202E38} = {62AAE0FE-4099-4A48-AA3C-F76F14C62655}
{0CF88F0B-6CCB-49B5-B41D-CDC193B51581} = {679E6084-0C45-4807-BFEE-D2FDA44B2188}
{C8FAB96F-F13E-4094-883C-2D38D39EE4A3} = {CC2C88C0-65F2-445D-BE78-973B840FE281}
{C34FCF48-1A98-4268-BFEE-6C9BFC7FD539} = {EDF8869A-C1E1-491B-BC9F-4A33F4DE1C73}
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{3CAF09A6-6ABD-41D9-BA57-9A822B8095F7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
@ -102,5 +105,9 @@ Global
{C8FAB96F-F13E-4094-883C-2D38D39EE4A3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C8FAB96F-F13E-4094-883C-2D38D39EE4A3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C8FAB96F-F13E-4094-883C-2D38D39EE4A3}.Release|Any CPU.Build.0 = Release|Any CPU
{C34FCF48-1A98-4268-BFEE-6C9BFC7FD539}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C34FCF48-1A98-4268-BFEE-6C9BFC7FD539}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C34FCF48-1A98-4268-BFEE-6C9BFC7FD539}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C34FCF48-1A98-4268-BFEE-6C9BFC7FD539}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

View File

@ -23,7 +23,7 @@ namespace Sample.SqlServer
{
o.ConnectionString = "";
o.AddSharding<SysUserModVirtualRoute>();
o.CreateIfNotExists((provider, config) =>
o.UseShardingCoreConfig((provider, config) =>
{
//如果是development就判断并且新建数据库如果不存在的话
config.EnsureCreated = provider.GetService<IHostEnvironment>().IsDevelopment();

View File

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace Samples.AutoByDate.SqlServer.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;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
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();
}
}
}

View File

@ -0,0 +1,22 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using ShardingCore;
namespace Samples.AutoByDate.SqlServer
{
/*
* @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;
}
}
}

View File

@ -0,0 +1,19 @@
using System;
using ShardingCore.Core;
namespace Samples.AutoByDate.SqlServer.Domain.Entities
{
/*
* @Author: xjm
* @Description:
* @Date: Tuesday, 02 February 2021 17:00:36
* @Email: 326308290@qq.com
*/
public class SysUserLogByDay:IShardingEntity
{
public int Id { get; set; }
public string Body { get; set; }
[ShardingKey]
public DateTime CreateTime { get; set; }
}
}

View File

@ -0,0 +1,24 @@
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Samples.AutoByDate.SqlServer.Domain.Entities;
namespace Samples.AutoByDate.SqlServer.Domain.Maps
{
/*
* @Author: xjm
* @Description:
* @Date: Tuesday, 02 February 2021 17:10:55
* @Email: 326308290@qq.com
*/
public class SysUserLogByDayMap:IEntityTypeConfiguration<SysUserLogByDay>
{
public void Configure(EntityTypeBuilder<SysUserLogByDay> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).ValueGeneratedOnAdd();
builder.Property(o => o.Body).HasMaxLength(128);
builder.ToTable(nameof(SysUserLogByDay));
}
}
}

View File

@ -0,0 +1,48 @@
using System;
using ChronusJob.Abstractions;
using ChronusJob.Jobs.Attributes;
using Samples.AutoByDate.SqlServer.Domain.Entities;
using ShardingCore.Core.PhysicTables;
using ShardingCore.Core.VirtualTables;
using ShardingCore.TableCreator;
namespace Samples.AutoByDate.SqlServer.Jobs
{
/*
* @Author: xjm
* @Description:
* @Date: Tuesday, 02 February 2021 17:24:17
* @Email: 326308290@qq.com
*/
public class AutoCreateTableByDay : IJob
{
/// <summary>
/// 每天中午12点执行,启动的时候执行以下
/// </summary>
/// <param name="virtualTableManager"></param>
/// <param name="tableCreator"></param>
[JobRun(Name = "定时创建分表组件",Cron = "0 0 12 * * ?",RunOnceOnStart = true)]
public void AutoCreateTable(IVirtualTableManager virtualTableManager, IShardingTableCreator tableCreator)
{
var allVirtualTables = virtualTableManager.GetAllVirtualTables();
foreach (var virtualTable in allVirtualTables)
{
if (virtualTable.EntityType == typeof(SysUserLogByDay))
{
var now = DateTime.Now.Date.AddDays(1);
var tail = virtualTable.GetVirtualRoute().ShardingKeyToTail(now);
try
{
tableCreator.CreateTable<SysUserLogByDay>(tail);
virtualTableManager.AddPhysicTable(virtualTable, new DefaultPhysicTable(virtualTable, tail));
}
catch (Exception e)
{
//ignore
}
}
}
}
}
}

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Samples.AutoByDate.SqlServer
{
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>(); });
}
}

View File

@ -0,0 +1,31 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:34492",
"sslPort": 44389
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Samples.AutoByDate.SqlServer": {
"commandName": "Project",
"dotnetRunMessages": "true",
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ChronusJob" Version="1.0.5" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.1" NoWarn="NU1605" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="5.0.1" NoWarn="NU1605" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\ShardingCore.SqlServer\ShardingCore.SqlServer.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using Samples.AutoByDate.SqlServer.Domain.Entities;
using ShardingCore.VirtualRoutes.Days;
namespace Samples.AutoByDate.SqlServer.Shardings
{
/*
* @Author: xjm
* @Description:
* @Date: Tuesday, 02 February 2021 17:14:53
* @Email: 326308290@qq.com
*/
public class SysUserLogByDayVirtualRoute:AbstractSimpleShardingDayKeyDateTimeVirtualRoute<SysUserLogByDay>
{
public override List<string> GetAllTails()
{
var beginTime = DateTime.Now.AddDays(-2);
var tails=new List<string>();
//提前创建表
var nowTimeStamp = DateTime.Now.AddDays(1).Date;
if (beginTime > nowTimeStamp)
throw new ArgumentException("起始时间不正确无法生成正确的表名");
var currentTimeStamp = beginTime;
while (currentTimeStamp <= nowTimeStamp)
{
var tail = ShardingKeyToTail(currentTimeStamp);
tails.Add(tail);
currentTimeStamp = currentTimeStamp.AddDays(1);
}
return tails;
}
}
}

View File

@ -0,0 +1,68 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ChronusJob;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using Samples.AutoByDate.SqlServer.Shardings;
using ShardingCore.SqlServer;
namespace Samples.AutoByDate.SqlServer
{
public class Startup
{
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.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo {Title = "Samples.AutoByDate.SqlServer", Version = "v1"}); });
services.AddShardingSqlServer(o =>
{
o.ConnectionString = "";
o.AddSharding<SysUserLogByDayVirtualRoute>();
o.UseShardingCoreConfig((provider, config) =>
{
//如果是development就判断并且新建数据库如果不存在的话
config.EnsureCreated = provider.GetService<IHostEnvironment>().IsDevelopment();
config.CreateShardingTableOnStart = true;
});
});
services.AddChronusJob();
}
// 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.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Samples.AutoByDate.SqlServer v1"));
}
app.UseShardingCore();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}
}

View File

@ -0,0 +1,15 @@
using System;
namespace Samples.AutoByDate.SqlServer
{
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; }
}
}

View File

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}

View File

@ -0,0 +1,10 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}

View File

@ -23,7 +23,7 @@ namespace ShardingCore.SqlServer
public bool HasSharding => ShardingRoutes.IsNotEmpty();
public Action<IServiceProvider, ShardingCoreConfig> ShardingCoreConfigConfigure { get; private set; }
public void CreateIfNotExists(Action<IServiceProvider, ShardingCoreConfig> function)
public void UseShardingCoreConfig(Action<IServiceProvider, ShardingCoreConfig> function)
{
ShardingCoreConfigConfigure = function;
}

View File

@ -15,10 +15,10 @@ namespace ShardingCore.Core.PhysicTables
public class DefaultPhysicTable:IPhysicTable
{
public DefaultPhysicTable(string originalName, IVirtualTable virtualTable, string tail)
public DefaultPhysicTable(IVirtualTable virtualTable, string tail)
{
VirtualTable = virtualTable;
OriginalName = originalName;
OriginalName = virtualTable.GetOriginalTableName();
Tail = tail;
}
public string FullName => $"{OriginalName}{TailPrefix}{Tail}";

View File

@ -100,7 +100,7 @@ namespace ShardingCore
}
//添加物理表
virtualTable.AddPhysicTable(new DefaultPhysicTable(virtualTable.GetOriginalTableName(), virtualTable, tail));
virtualTable.AddPhysicTable(new DefaultPhysicTable(virtualTable, tail));
}
}
}

View File

@ -50,7 +50,7 @@ namespace ShardingCore.Test50
o.ConnectionString = hostBuilderContext.Configuration.GetSection("SqlServer")["ConnectionString"];
o.AddSharding<SysUserModVirtualRoute>();
o.AddSharding<SysUserSalaryVirtualRoute>();
o.CreateIfNotExists((provider, config) =>
o.UseShardingCoreConfig((provider, config) =>
{
config.EnsureCreated = true;
});