diff --git a/ShardingCore.sln b/ShardingCore.sln index 0bf2e686..1c4ef5bb 100644 --- a/ShardingCore.sln +++ b/ShardingCore.sln @@ -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 diff --git a/samples/Sample.SqlServer/Startup.cs b/samples/Sample.SqlServer/Startup.cs index 52b85d1e..a81a6346 100644 --- a/samples/Sample.SqlServer/Startup.cs +++ b/samples/Sample.SqlServer/Startup.cs @@ -23,7 +23,7 @@ namespace Sample.SqlServer { o.ConnectionString = ""; o.AddSharding(); - o.CreateIfNotExists((provider, config) => + o.UseShardingCoreConfig((provider, config) => { //如果是development就判断并且新建数据库如果不存在的话 config.EnsureCreated = provider.GetService().IsDevelopment(); diff --git a/samples/Samples.AutoByDate.SqlServer/Controllers/WeatherForecastController.cs b/samples/Samples.AutoByDate.SqlServer/Controllers/WeatherForecastController.cs new file mode 100644 index 00000000..0fae6ac2 --- /dev/null +++ b/samples/Samples.AutoByDate.SqlServer/Controllers/WeatherForecastController.cs @@ -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 _logger; + + public WeatherForecastController(ILogger logger) + { + _logger = logger; + } + + [HttpGet] + public IEnumerable 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(); + } + } +} \ No newline at end of file diff --git a/samples/Samples.AutoByDate.SqlServer/DIExtension.cs b/samples/Samples.AutoByDate.SqlServer/DIExtension.cs new file mode 100644 index 00000000..a2fc648d --- /dev/null +++ b/samples/Samples.AutoByDate.SqlServer/DIExtension.cs @@ -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(); + shardingBootstrapper.Start(); + return app; + } + } +} \ No newline at end of file diff --git a/samples/Samples.AutoByDate.SqlServer/Domain/Entities/SysUserLogByDay.cs b/samples/Samples.AutoByDate.SqlServer/Domain/Entities/SysUserLogByDay.cs new file mode 100644 index 00000000..d42bf1a5 --- /dev/null +++ b/samples/Samples.AutoByDate.SqlServer/Domain/Entities/SysUserLogByDay.cs @@ -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; } + } +} \ No newline at end of file diff --git a/samples/Samples.AutoByDate.SqlServer/Domain/Maps/SysUserLogByDayMap.cs b/samples/Samples.AutoByDate.SqlServer/Domain/Maps/SysUserLogByDayMap.cs new file mode 100644 index 00000000..e589c2dd --- /dev/null +++ b/samples/Samples.AutoByDate.SqlServer/Domain/Maps/SysUserLogByDayMap.cs @@ -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 + { + public void Configure(EntityTypeBuilder builder) + { + builder.HasKey(o => o.Id); + builder.Property(o => o.Id).ValueGeneratedOnAdd(); + builder.Property(o => o.Body).HasMaxLength(128); + builder.ToTable(nameof(SysUserLogByDay)); + } + } +} \ No newline at end of file diff --git a/samples/Samples.AutoByDate.SqlServer/Jobs/AutoCreateTableByDay.cs b/samples/Samples.AutoByDate.SqlServer/Jobs/AutoCreateTableByDay.cs new file mode 100644 index 00000000..f905c592 --- /dev/null +++ b/samples/Samples.AutoByDate.SqlServer/Jobs/AutoCreateTableByDay.cs @@ -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 + { + /// + /// 每天中午12点执行,启动的时候执行以下 + /// + /// + /// + [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(tail); + virtualTableManager.AddPhysicTable(virtualTable, new DefaultPhysicTable(virtualTable, tail)); + } + catch (Exception e) + { + //ignore + } + } + } + } + } +} \ No newline at end of file diff --git a/samples/Samples.AutoByDate.SqlServer/Program.cs b/samples/Samples.AutoByDate.SqlServer/Program.cs new file mode 100644 index 00000000..1d90280f --- /dev/null +++ b/samples/Samples.AutoByDate.SqlServer/Program.cs @@ -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(); }); + } +} \ No newline at end of file diff --git a/samples/Samples.AutoByDate.SqlServer/Properties/launchSettings.json b/samples/Samples.AutoByDate.SqlServer/Properties/launchSettings.json new file mode 100644 index 00000000..70f36e40 --- /dev/null +++ b/samples/Samples.AutoByDate.SqlServer/Properties/launchSettings.json @@ -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" + } + } + } +} diff --git a/samples/Samples.AutoByDate.SqlServer/Samples.AutoByDate.SqlServer.csproj b/samples/Samples.AutoByDate.SqlServer/Samples.AutoByDate.SqlServer.csproj new file mode 100644 index 00000000..f2f2b379 --- /dev/null +++ b/samples/Samples.AutoByDate.SqlServer/Samples.AutoByDate.SqlServer.csproj @@ -0,0 +1,18 @@ + + + + net5.0 + + + + + + + + + + + + + + diff --git a/samples/Samples.AutoByDate.SqlServer/Shardings/SysUserLogByDayVirtualRoute.cs b/samples/Samples.AutoByDate.SqlServer/Shardings/SysUserLogByDayVirtualRoute.cs new file mode 100644 index 00000000..50cce70f --- /dev/null +++ b/samples/Samples.AutoByDate.SqlServer/Shardings/SysUserLogByDayVirtualRoute.cs @@ -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 + { + public override List GetAllTails() + { + var beginTime = DateTime.Now.AddDays(-2); + + var tails=new List(); + //提前创建表 + 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; + } + } +} \ No newline at end of file diff --git a/samples/Samples.AutoByDate.SqlServer/Startup.cs b/samples/Samples.AutoByDate.SqlServer/Startup.cs new file mode 100644 index 00000000..067f59ac --- /dev/null +++ b/samples/Samples.AutoByDate.SqlServer/Startup.cs @@ -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(); + o.UseShardingCoreConfig((provider, config) => + { + //如果是development就判断并且新建数据库如果不存在的话 + config.EnsureCreated = provider.GetService().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(); }); + } + } +} \ No newline at end of file diff --git a/samples/Samples.AutoByDate.SqlServer/WeatherForecast.cs b/samples/Samples.AutoByDate.SqlServer/WeatherForecast.cs new file mode 100644 index 00000000..316e9fa0 --- /dev/null +++ b/samples/Samples.AutoByDate.SqlServer/WeatherForecast.cs @@ -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; } + } +} \ No newline at end of file diff --git a/samples/Samples.AutoByDate.SqlServer/appsettings.Development.json b/samples/Samples.AutoByDate.SqlServer/appsettings.Development.json new file mode 100644 index 00000000..8983e0fc --- /dev/null +++ b/samples/Samples.AutoByDate.SqlServer/appsettings.Development.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + } +} diff --git a/samples/Samples.AutoByDate.SqlServer/appsettings.json b/samples/Samples.AutoByDate.SqlServer/appsettings.json new file mode 100644 index 00000000..d9d9a9bf --- /dev/null +++ b/samples/Samples.AutoByDate.SqlServer/appsettings.json @@ -0,0 +1,10 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + }, + "AllowedHosts": "*" +} diff --git a/src/ShardingCore.SqlServer/SqlServerOptions.cs b/src/ShardingCore.SqlServer/SqlServerOptions.cs index 48e54aa9..69328a07 100644 --- a/src/ShardingCore.SqlServer/SqlServerOptions.cs +++ b/src/ShardingCore.SqlServer/SqlServerOptions.cs @@ -23,7 +23,7 @@ namespace ShardingCore.SqlServer public bool HasSharding => ShardingRoutes.IsNotEmpty(); public Action ShardingCoreConfigConfigure { get; private set; } - public void CreateIfNotExists(Action function) + public void UseShardingCoreConfig(Action function) { ShardingCoreConfigConfigure = function; } diff --git a/src/ShardingCore/Core/PhysicTables/DefaultPhysicTable.cs b/src/ShardingCore/Core/PhysicTables/DefaultPhysicTable.cs index 82b7541c..15d2dae1 100644 --- a/src/ShardingCore/Core/PhysicTables/DefaultPhysicTable.cs +++ b/src/ShardingCore/Core/PhysicTables/DefaultPhysicTable.cs @@ -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}"; diff --git a/src/ShardingCore/ShardingBootstrapper.cs b/src/ShardingCore/ShardingBootstrapper.cs index 4692ae17..0a7e4425 100644 --- a/src/ShardingCore/ShardingBootstrapper.cs +++ b/src/ShardingCore/ShardingBootstrapper.cs @@ -100,7 +100,7 @@ namespace ShardingCore } //添加物理表 - virtualTable.AddPhysicTable(new DefaultPhysicTable(virtualTable.GetOriginalTableName(), virtualTable, tail)); + virtualTable.AddPhysicTable(new DefaultPhysicTable(virtualTable, tail)); } } } diff --git a/test/ShardingCore.Test50/Startup.cs b/test/ShardingCore.Test50/Startup.cs index bcffe094..136393fb 100644 --- a/test/ShardingCore.Test50/Startup.cs +++ b/test/ShardingCore.Test50/Startup.cs @@ -50,7 +50,7 @@ namespace ShardingCore.Test50 o.ConnectionString = hostBuilderContext.Configuration.GetSection("SqlServer")["ConnectionString"]; o.AddSharding(); o.AddSharding(); - o.CreateIfNotExists((provider, config) => + o.UseShardingCoreConfig((provider, config) => { config.EnsureCreated = true; });