7.x.1.19-preview1 [#252]

This commit is contained in:
xuejiaming 2023-11-24 08:18:05 +08:00
parent 531367bc79
commit 626bbb0f4c
52 changed files with 5135 additions and 14 deletions

View File

@ -79,6 +79,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ShardingCore7", "src7\Shard
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src7", "src7", "{A5321A3E-8539-4E2A-889C-8E91989EECBD}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src7", "src7", "{A5321A3E-8539-4E2A-889C-8E91989EECBD}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShardingCore.Test7x", "src\ShardingCore.Test7x\ShardingCore.Test7x.csproj", "{FC6C1017-69D5-44E0-8C4C-99B6F476FB55}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@ -201,6 +203,10 @@ Global
{A308D253-A072-40EC-AA97-15EE82BB8AAD}.Debug|Any CPU.Build.0 = Debug|Any CPU {A308D253-A072-40EC-AA97-15EE82BB8AAD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A308D253-A072-40EC-AA97-15EE82BB8AAD}.Release|Any CPU.ActiveCfg = Release|Any CPU {A308D253-A072-40EC-AA97-15EE82BB8AAD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A308D253-A072-40EC-AA97-15EE82BB8AAD}.Release|Any CPU.Build.0 = Release|Any CPU {A308D253-A072-40EC-AA97-15EE82BB8AAD}.Release|Any CPU.Build.0 = Release|Any CPU
{FC6C1017-69D5-44E0-8C4C-99B6F476FB55}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FC6C1017-69D5-44E0-8C4C-99B6F476FB55}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FC6C1017-69D5-44E0-8C4C-99B6F476FB55}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FC6C1017-69D5-44E0-8C4C-99B6F476FB55}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
@ -235,6 +241,7 @@ Global
{F0393C32-2285-4F47-AC61-C1BA1CAC269D} = {B11D7DF7-A907-407E-8BF1-35B430413557} {F0393C32-2285-4F47-AC61-C1BA1CAC269D} = {B11D7DF7-A907-407E-8BF1-35B430413557}
{3B5A4B03-5190-41A8-8E4B-F95A79A5C018} = {EDF8869A-C1E1-491B-BC9F-4A33F4DE1C73} {3B5A4B03-5190-41A8-8E4B-F95A79A5C018} = {EDF8869A-C1E1-491B-BC9F-4A33F4DE1C73}
{A308D253-A072-40EC-AA97-15EE82BB8AAD} = {A5321A3E-8539-4E2A-889C-8E91989EECBD} {A308D253-A072-40EC-AA97-15EE82BB8AAD} = {A5321A3E-8539-4E2A-889C-8E91989EECBD}
{FC6C1017-69D5-44E0-8C4C-99B6F476FB55} = {CC2C88C0-65F2-445D-BE78-973B840FE281}
EndGlobalSection EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {8C07A667-E8B4-43C7-8053-721584BAD291} SolutionGuid = {8C07A667-E8B4-43C7-8053-721584BAD291}

View File

@ -1,11 +1,11 @@
:start :start
::定义版本 ::定义版本
set EFCORE8=7.8.1.19 set EFCORE8=7.8.1.19-preview1
set EFCORE7=7.7.1.19 set EFCORE7=7.7.1.19-preview1
set EFCORE6=7.6.1.19 set EFCORE6=7.6.1.19-preview1
set EFCORE5=7.5.1.19 set EFCORE5=7.5.1.19-preview1
set EFCORE3=7.3.1.19 set EFCORE3=7.3.1.19-preview1
set EFCORE2=7.2.1.19 set EFCORE2=7.2.1.19-preview1
::删除所有bin与obj下的文件 ::删除所有bin与obj下的文件
@echo off @echo off

View File

@ -16,7 +16,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\src\ShardingCore\ShardingCore7.csproj" /> <ProjectReference Include="..\..\src7\ShardingCore7\ShardingCore7.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -0,0 +1,196 @@
using System;
using System.Text;
namespace ShardingCore.Test.Common
{/// <summary>
/// 雪花ID
/// Twitter_Snowflake
/// SnowFlake的结构如下(每部分用-分开)
/// 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000
/// 1位标识由于long基本类型在Java中是带符号的最高位是符号位正数是0负数是1所以id一般是正数最高位是0
/// 41位时间截(毫秒级)注意41位时间截不是存储当前时间的时间截而是存储时间截的差值当前时间截 - 开始时间截)得到的值),
/// 41位的时间截可以使用69年年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69
/// 这里的的开始时间截一般是我们的id生成器开始使用的时间由我们程序来指定的如下下面程序IdWorker类的startTime属性
/// 10位的数据机器位可以部署在1024个节点包括5位datacenterId和5位workerId
/// 12位序列毫秒内的计数12位的计数顺序号支持每个节点每毫秒(同一机器,同一时间截)产生4096个ID序号
/// 总共加起来刚好64位为一个Long型。
/// SnowFlake的优点是整体上按照时间自增排序并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分)
/// 并且效率较高经测试SnowFlake单机每秒都能够产生出极限4,096,000个ID来
/// </summary>
public class SnowflakeId
{
// 开始时间截 (new DateTime(2020, 1, 1).ToUniversalTime() - Jan1st1970).TotalMilliseconds
private const long twepoch = 1577808000000L;
// 机器id所占的位数
private const int workerIdBits = 5;
// 数据标识id所占的位数
private const int datacenterIdBits = 5;
// 支持的最大机器id结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数)
private const long maxWorkerId = -1L ^ (-1L << workerIdBits);
// 支持的最大数据标识id结果是31
private const long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
// 序列在id中占的位数
private const int sequenceBits = 12;
// 数据标识id向左移17位(12+5)
private const int datacenterIdShift = sequenceBits + workerIdBits;
// 机器ID向左移12位
private const int workerIdShift = sequenceBits;
// 时间截向左移22位(5+5+12)
private const int timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
// 生成序列的掩码这里为4095 (0b111111111111=0xfff=4095)
private const long sequenceMask = -1L ^ (-1L << sequenceBits);
// 数据中心ID(0~31)
public long datacenterId { get; private set; }
// 工作机器ID(0~31)
public long workerId { get; private set; }
// 毫秒内序列(0~4095)
public long sequence { get; private set; }
// 上次生成ID的时间截
public long lastTimestamp { get; private set; }
/// <summary>
/// 雪花ID
/// </summary>
/// <param name="datacenterId">数据中心ID</param>
/// <param name="workerId">工作机器ID</param>
public SnowflakeId(long datacenterId, long workerId)
{
if (datacenterId > maxDatacenterId || datacenterId < 0)
{
throw new Exception(string.Format("datacenter Id can't be greater than {0} or less than 0", maxDatacenterId));
}
if (workerId > maxWorkerId || workerId < 0)
{
throw new Exception(string.Format("worker Id can't be greater than {0} or less than 0", maxWorkerId));
}
this.workerId = workerId;
this.datacenterId = datacenterId;
this.sequence = 0L;
this.lastTimestamp = -1L;
}
/// <summary>
/// 获得下一个ID
/// </summary>
/// <returns></returns>
public long NextId()
{
lock (this)
{
long timestamp = GetCurrentTimestamp();
if (timestamp > lastTimestamp) //时间戳改变,毫秒内序列重置
{
sequence = 0L;
}
else if (timestamp == lastTimestamp) //如果是同一时间生成的,则进行毫秒内序列
{
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) //毫秒内序列溢出
{
timestamp = GetNextTimestamp(lastTimestamp); //阻塞到下一个毫秒,获得新的时间戳
}
}
else //当前时间小于上一次ID生成的时间戳证明系统时钟被回拨此时需要做回拨处理
{
sequence = (sequence + 1) & sequenceMask;
if (sequence > 0)
{
timestamp = lastTimestamp; //停留在最后一次时间戳上,等待系统时间追上后即完全度过了时钟回拨问题。
}
else //毫秒内序列溢出
{
timestamp = lastTimestamp + 1; //直接进位到下一个毫秒
}
//throw new Exception(string.Format("Clock moved backwards. Refusing to generate id for {0} milliseconds", lastTimestamp - timestamp));
}
lastTimestamp = timestamp; //上次生成ID的时间截
//移位并通过或运算拼到一起组成64位的ID
var id = ((timestamp - twepoch) << timestampLeftShift)
| (datacenterId << datacenterIdShift)
| (workerId << workerIdShift)
| sequence;
return id;
}
}
/// <summary>
/// 解析雪花ID
/// </summary>
/// <returns></returns>
public static DateTime AnalyzeIdToDateTime(long Id)
{
var timestamp = (Id >> timestampLeftShift);
var time = Jan1st1970.AddMilliseconds(timestamp + twepoch);
return time.ToLocalTime();
}
/// <summary>
/// 解析雪花ID
/// </summary>
/// <returns></returns>
public static string AnalyzeId(long Id)
{
StringBuilder sb = new StringBuilder();
var timestamp = (Id >> timestampLeftShift);
var time = Jan1st1970.AddMilliseconds(timestamp + twepoch);
sb.Append(time.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss:fff"));
var datacenterId = (Id ^ (timestamp << timestampLeftShift)) >> datacenterIdShift;
sb.Append("_" + datacenterId);
var workerId = (Id ^ ((timestamp << timestampLeftShift) | (datacenterId << datacenterIdShift))) >> workerIdShift;
sb.Append("_" + workerId);
var sequence = Id & sequenceMask;
sb.Append("_" + sequence);
return sb.ToString();
}
/// <summary>
/// 阻塞到下一个毫秒,直到获得新的时间戳
/// </summary>
/// <param name="lastTimestamp">上次生成ID的时间截</param>
/// <returns>当前时间戳</returns>
private static long GetNextTimestamp(long lastTimestamp)
{
long timestamp = GetCurrentTimestamp();
while (timestamp <= lastTimestamp)
{
timestamp = GetCurrentTimestamp();
}
return timestamp;
}
/// <summary>
/// 获取当前时间戳
/// </summary>
/// <returns></returns>
private static long GetCurrentTimestamp()
{
return (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds;
}
private static readonly DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
}
}

View File

@ -0,0 +1,12 @@
using System;
namespace ShardingCore.Test.Domain.Entities
{
public class LogDay
{
public Guid Id { get; set; }
public string LogLevel { get; set; }
public string LogBody { get; set; }
public DateTime LogTime { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShardingCore.Test.Domain.Entities
{
public class LogDayLong
{
public Guid Id { get; set; }
public string LogLevel { get; set; }
public string LogBody { get; set; }
public long LogTime { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShardingCore.Test.Domain.Entities
{
public class LogMonthLong
{
public string Id { get; set; }
public string Body { get; set; }
public long LogTime { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShardingCore.Test.Domain.Entities
{
public class LogNoSharding
{
public string Id { get; set; }
public string Body { get; set; }
public DateTime CreationTime { get; set; }
}
}

View File

@ -0,0 +1,12 @@
using System;
namespace ShardingCore.Test.Domain.Entities
{
public class LogWeekDateTime
{
public string Id { get; set; }
public string Body { get; set; }
public DateTime LogTime { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShardingCore.Test.Domain.Entities
{
public class LogWeekTimeLong
{
public string Id { get; set; }
public string Body { get; set; }
public long LogTime { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShardingCore.Test.Domain.Entities
{
public class LogYearDateTime
{
public Guid Id { get; set; }
public string LogBody { get; set; }
public DateTime LogTime { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShardingCore.Test.Domain.Entities
{
public class LogYearLong
{
public string Id { get; set; }
public string LogBody { get; set; }
public long LogTime { get; set; }
}
}

View File

@ -0,0 +1,11 @@
using System;
namespace ShardingCore.Test.Domain.Entities
{
public class MultiShardingOrder
{
public long Id { get; set; }
public string Name { get; set; }
public DateTime CreateTime { get; set; }
}
}

View File

@ -0,0 +1,13 @@
using System;
using ShardingCore.Core;
namespace ShardingCore.Test.Domain.Entities
{
public class Order
{
public Guid Id { get; set; }
public string Area { get; set; }
public long Money { get; set; }
public DateTime CreateTime { get; set; }
}
}

View File

@ -0,0 +1,32 @@
namespace ShardingCore.Test.Domain.Entities
{
/*
* @Author: xjm
* @Description:
* @Date: Thursday, 14 January 2021 15:36:43
* @Email: 326308290@qq.com
*/
public class SysUserMod: IId
{
/// <summary>
/// 用户Id用于分表
/// </summary>
public string Id { get; set; }
/// <summary>
/// 用户名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 用户姓名
/// </summary>
public int Age { get; set; }
public int AgeGroup { get; set; }
}
public interface IId
{
string Id { get; set; }
}
}

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShardingCore.Test.Domain.Entities
{
public class SysUserModInt
{
/// <summary>
/// 用户Id用于分表
/// </summary>
public int Id { get; set; }
/// <summary>
/// 用户名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 用户姓名
/// </summary>
public int Age { get; set; }
public int AgeGroup { get; set; }
}
}

View File

@ -0,0 +1,39 @@
namespace ShardingCore.Test.Domain.Entities
{
/*
* @Author: xjm
* @Description:
* @Date: Monday, 01 February 2021 15:43:22
* @Email: 326308290@qq.com
*/
public class SysUserSalary
{
public string Id { get; set; }
public string UserId { get; set; }
/// <summary>
/// 每月的金额
/// </summary>
public int DateOfMonth { get; set; }
/// <summary>
/// 工资
/// </summary>
public int Salary { get; set; }
/// <summary>
/// 工资
/// </summary>
public long SalaryLong { get; set; }
/// <summary>
/// 工资
/// </summary>
public decimal SalaryDecimal { get; set; }
/// <summary>
/// 工资
/// </summary>
public double SalaryDouble { get; set; }
/// <summary>
/// 工资
/// </summary>
public float SalaryFloat { get; set; }
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShardingCore.Test.Domain.Entities;
namespace ShardingCore.Test.Domain.Maps
{
public class LogDayLongMap:IEntityTypeConfiguration<LogDayLong>
{
public void Configure(EntityTypeBuilder<LogDayLong> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.LogLevel).IsRequired().IsUnicode(false).HasMaxLength(32);
builder.Property(o => o.LogBody).IsRequired().HasMaxLength(256);
builder.ToTable(nameof(LogDayLong));
}
}
}

View File

@ -0,0 +1,17 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShardingCore.Test.Domain.Entities;
namespace ShardingCore.Test.Domain.Maps
{
public class LogDayMap:IEntityTypeConfiguration<LogDay>
{
public void Configure(EntityTypeBuilder<LogDay> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.LogLevel).IsRequired().IsUnicode(false).HasMaxLength(32);
builder.Property(o => o.LogBody).IsRequired().HasMaxLength(256);
builder.ToTable(nameof(LogDay));
}
}
}

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShardingCore.Test.Domain.Entities;
namespace ShardingCore.Test.Domain.Maps
{
public class LogMonthLongMap:IEntityTypeConfiguration<LogMonthLong>
{
public void Configure(EntityTypeBuilder<LogMonthLong> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).IsRequired().IsUnicode(false).HasMaxLength(50);
builder.Property(o => o.Body).HasMaxLength(128);
builder.ToTable(nameof(LogMonthLong));
}
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShardingCore.Test.Domain.Entities;
namespace ShardingCore.Test.Domain.Maps
{
public class LogNoShardingMap:IEntityTypeConfiguration<LogNoSharding>
{
public void Configure(EntityTypeBuilder<LogNoSharding> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).IsRequired().HasMaxLength(50);
builder.Property(o => o.Body).HasMaxLength(256);
builder.ToTable(nameof(LogNoSharding));
}
}
}

View File

@ -0,0 +1,17 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShardingCore.Test.Domain.Entities;
namespace ShardingCore.Test.Domain.Maps
{
public class LogWeekDateTimeMap:IEntityTypeConfiguration<LogWeekDateTime>
{
public void Configure(EntityTypeBuilder<LogWeekDateTime> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).IsRequired().IsUnicode(false).HasMaxLength(50);
builder.Property(o => o.Body).HasMaxLength(128);
builder.ToTable(nameof(LogWeekDateTime));
}
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShardingCore.Test.Domain.Entities;
namespace ShardingCore.Test.Domain.Maps
{
public class LogWeekTimeLongMap : IEntityTypeConfiguration<LogWeekTimeLong>
{
public void Configure(EntityTypeBuilder<LogWeekTimeLong> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).IsRequired().IsUnicode(false).HasMaxLength(50);
builder.Property(o => o.Body).HasMaxLength(128);
builder.ToTable(nameof(LogWeekTimeLong));
}
}
}

View File

@ -0,0 +1,22 @@

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShardingCore.Test.Domain.Entities;
namespace ShardingCore.Test.Domain.Maps
{
public class LogYearDateTimeMap : IEntityTypeConfiguration<LogYearDateTime>
{
public void Configure(EntityTypeBuilder<LogYearDateTime> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.LogBody).IsRequired().HasMaxLength(256);
builder.ToTable(nameof(LogYearDateTime));
}
}
}

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShardingCore.Test.Domain.Entities;
namespace ShardingCore.Test.Domain.Maps
{
public class LogYearLongMap:IEntityTypeConfiguration<LogYearLong>
{
public void Configure(EntityTypeBuilder<LogYearLong> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).IsRequired().IsUnicode(false).HasMaxLength(50);
builder.Property(o => o.LogBody).HasMaxLength(128);
builder.ToTable(nameof(LogYearLong));
}
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShardingCore.Test.Domain.Entities;
namespace ShardingCore.Test.Domain.Maps
{
public class MultiShardingOrderMap:IEntityTypeConfiguration<MultiShardingOrder>
{
public void Configure(EntityTypeBuilder<MultiShardingOrder> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).ValueGeneratedNever();
builder.Property(o => o.Name).IsRequired().IsUnicode(false).HasMaxLength(50);
builder.ToTable(nameof(MultiShardingOrder));
}
}
}

View File

@ -0,0 +1,16 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShardingCore.Test.Domain.Entities;
namespace ShardingCore.Test.Domain.Maps
{
public class OrderMap:IEntityTypeConfiguration<Order>
{
public void Configure(EntityTypeBuilder<Order> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Area).IsRequired().IsUnicode(false).HasMaxLength(20);
builder.ToTable(nameof(Order));
}
}
}

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShardingCore.Test.Domain.Entities;
namespace ShardingCore.Test.Domain.Maps
{
public class SysUserModIntMap:IEntityTypeConfiguration<SysUserModInt>
{
public void Configure(EntityTypeBuilder<SysUserModInt> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).ValueGeneratedNever();
builder.Property(o => o.Name).HasMaxLength(128);
builder.ToTable(nameof(SysUserModInt));
}
}
}

View File

@ -0,0 +1,23 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShardingCore.Test.Domain.Entities;
namespace ShardingCore.Test.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));
}
}
}

View File

@ -0,0 +1,23 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShardingCore.Test.Domain.Entities;
namespace ShardingCore.Test.Domain.Maps
{
/*
* @Author: xjm
* @Description:
* @Date: Monday, 01 February 2021 15:42:35
* @Email: 326308290@qq.com
*/
public class SysUserSalaryMap:IEntityTypeConfiguration<SysUserSalary>
{
public void Configure(EntityTypeBuilder<SysUserSalary> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).IsRequired().HasMaxLength(128);
builder.Property(o => o.UserId).IsRequired().HasMaxLength(128);
builder.ToTable(nameof(SysUserSalary));
}
}
}

View File

@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<DefineConstants>TRACE;DEBUG;EFCORE7Test;</DefineConstants>
<AssemblyName>ShardingCore.Test</AssemblyName>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="6.0.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="7.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.0" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="Xunit.DependencyInjection" Version="8.5.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src7\ShardingCore7\ShardingCore7.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,48 @@
using Microsoft.EntityFrameworkCore;
using ShardingCore.Core.VirtualRoutes.TableRoutes.RouteTails.Abstractions;
using ShardingCore.Sharding;
using ShardingCore.Sharding.Abstractions;
using ShardingCore.Test.Domain.Maps;
namespace ShardingCore.Test
{
/*
* @Author: xjm
* @Description:
* @Date: 2021/8/15 10:21:03
* @Ver: 1.0
* @Email: 326308290@qq.com
*/
public class ShardingDefaultDbContext:AbstractShardingDbContext, IShardingTableDbContext
{
public ShardingDefaultDbContext(DbContextOptions<ShardingDefaultDbContext> options) : base(options)
{
}
//protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
//{
// base.OnConfiguring(optionsBuilder);
// optionsBuilder.UseLazyLoadingProxies();
//}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfiguration(new SysUserModMap());
modelBuilder.ApplyConfiguration(new SysUserSalaryMap());
modelBuilder.ApplyConfiguration(new OrderMap());
modelBuilder.ApplyConfiguration(new LogDayMap());
modelBuilder.ApplyConfiguration(new LogWeekDateTimeMap());
modelBuilder.ApplyConfiguration(new LogWeekTimeLongMap());
modelBuilder.ApplyConfiguration(new LogYearDateTimeMap());
modelBuilder.ApplyConfiguration(new LogNoShardingMap());
modelBuilder.ApplyConfiguration(new LogMonthLongMap());
modelBuilder.ApplyConfiguration(new LogYearLongMap());
modelBuilder.ApplyConfiguration(new SysUserModIntMap());
modelBuilder.ApplyConfiguration(new LogDayLongMap());
modelBuilder.ApplyConfiguration(new MultiShardingOrderMap());
}
public IRouteTail RouteTail { get; set; }
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Helpers;
using ShardingCore.Test.Domain.Entities;
using ShardingCore.VirtualRoutes.Days;
namespace ShardingCore.Test.Shardings
{
public class LogDayLongVirtualRoute:AbstractSimpleShardingDayKeyLongVirtualTableRoute<LogDayLong>
{
//public override bool? EnableRouteParseCompileCache => true;
protected override bool EnableHintRoute => true;
public override void Configure(EntityMetadataTableBuilder<LogDayLong> builder)
{
builder.ShardingProperty(o => o.LogTime);
}
public override bool AutoCreateTableByTime()
{
return true;
}
public override DateTime GetBeginTime()
{
return new DateTime(2021, 1, 1);
}
protected override List<string> CalcTailsOnStart()
{
var beginTime = GetBeginTime().Date;
var tails = new List<string>();
//提前创建表
var nowTimeStamp = new DateTime(2021,11,20).Date;
if (beginTime > nowTimeStamp)
throw new ArgumentException("begin time error");
var currentTimeStamp = beginTime;
while (currentTimeStamp <= nowTimeStamp)
{
var currentTimeStampLong = ShardingCoreHelper.ConvertDateTimeToLong(currentTimeStamp);
var tail = TimeFormatToTail(currentTimeStampLong);
tails.Add(tail);
currentTimeStamp = currentTimeStamp.AddDays(1);
}
return tails;
}
}
}

View File

@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Sharding.PaginationConfigurations;
using ShardingCore.Test.Domain.Entities;
using ShardingCore.Test.Shardings.PaginationConfigs;
using ShardingCore.VirtualRoutes.Days;
namespace ShardingCore.Test.Shardings
{
public class LogDayVirtualTableRoute:AbstractSimpleShardingDayKeyDateTimeVirtualTableRoute<LogDay>
{
//public override bool? EnableRouteParseCompileCache => true;
protected override bool EnableHintRoute => true;
public override DateTime GetBeginTime()
{
return new DateTime(2021, 1, 1);
}
public override void Configure(EntityMetadataTableBuilder<LogDay> builder)
{
builder.ShardingProperty(o => o.LogTime);
builder.TableSeparator(string.Empty);
}
public override IPaginationConfiguration<LogDay> CreatePaginationConfiguration()
{
return new LogDayPaginationConfiguration();
}
public override bool AutoCreateTableByTime()
{
return true;
}
protected override List<string> CalcTailsOnStart()
{
var beginTime = GetBeginTime().Date;
var tails = new List<string>();
//提前创建表
var nowTimeStamp = new DateTime(2021,11,20).Date;
if (beginTime > nowTimeStamp)
throw new ArgumentException("begin time error");
var currentTimeStamp = beginTime;
while (currentTimeStamp <= nowTimeStamp)
{
var tail = ShardingKeyToTail(currentTimeStamp);
tails.Add(tail);
currentTimeStamp = currentTimeStamp.AddDays(1);
}
return tails;
}
}
}

View File

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Test.Domain.Entities;
using ShardingCore.Test.Domain.Maps;
using ShardingCore.VirtualRoutes.Months;
namespace ShardingCore.Test.Shardings
{
public class LogMonthLongvirtualRoute:AbstractSimpleShardingMonthKeyLongVirtualTableRoute<LogMonthLong>
{
//public override bool? EnableRouteParseCompileCache => true;
protected override bool EnableHintRoute => true;
public override bool AutoCreateTableByTime()
{
return true;
}
public override DateTime GetBeginTime()
{
return new DateTime(2021, 1, 1);
}
public override void Configure(EntityMetadataTableBuilder<LogMonthLong> builder)
{
builder.ShardingProperty(o => o.LogTime);
}
}
}

View File

@ -0,0 +1,28 @@
using System;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Test.Domain.Entities;
using ShardingCore.VirtualRoutes.Weeks;
namespace ShardingCore.Test.Shardings
{
public class LogWeekDateTimeVirtualTableRoute:AbstractSimpleShardingWeekKeyDateTimeVirtualTableRoute<LogWeekDateTime>
{
//public override bool? EnableRouteParseCompileCache => true;
protected override bool EnableHintRoute => true;
public override bool AutoCreateTableByTime()
{
return true;
}
public override DateTime GetBeginTime()
{
return new DateTime(2021, 1, 1);
}
public override void Configure(EntityMetadataTableBuilder<LogWeekDateTime> builder)
{
builder.ShardingProperty(o => o.LogTime);
}
}
}

View File

@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Test.Domain.Entities;
using ShardingCore.VirtualRoutes.Weeks;
namespace ShardingCore.Test.Shardings
{
public class LogWeekTimeLongVirtualTableRoute : AbstractSimpleShardingWeekKeyLongVirtualTableRoute<LogWeekTimeLong>
{
//public override bool? EnableRouteParseCompileCache => true;
protected override bool EnableHintRoute => true;
public override bool AutoCreateTableByTime()
{
return true;
}
public override DateTime GetBeginTime()
{
return new DateTime(2021, 1, 1);
}
public override void Configure(EntityMetadataTableBuilder<LogWeekTimeLong> builder)
{
builder.ShardingProperty(o => o.LogTime);
}
}
}

View File

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Test.Domain.Entities;
using ShardingCore.VirtualRoutes.Years;
namespace ShardingCore.Test.Shardings
{
public class LogYearDateTimeVirtualRoute:AbstractSimpleShardingYearKeyDateTimeVirtualTableRoute<LogYearDateTime>
{
//public override bool? EnableRouteParseCompileCache => true;
protected override bool EnableHintRoute => true;
public override bool AutoCreateTableByTime()
{
return true;
}
public override DateTime GetBeginTime()
{
return new DateTime(2020, 1, 1);
}
public override void Configure(EntityMetadataTableBuilder<LogYearDateTime> builder)
{
builder.ShardingProperty(o => o.LogTime);
}
}
}

View File

@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Test.Domain.Entities;
using ShardingCore.VirtualRoutes.Years;
namespace ShardingCore.Test.Shardings
{
public class LogYearLongVirtualRoute:AbstractSimpleShardingYearKeyLongVirtualTableRoute<LogYearLong>
{
//public override bool? EnableRouteParseCompileCache => true;
protected override bool EnableHintRoute => true;
public override void Configure(EntityMetadataTableBuilder<LogYearLong> builder)
{
builder.ShardingProperty(o => o.LogTime);
}
public override bool AutoCreateTableByTime()
{
return true;
}
public override DateTime GetBeginTime()
{
return new DateTime(2021, 1, 1);
}
}
}

View File

@ -0,0 +1,79 @@
using System;
using System.Linq.Expressions;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Core.VirtualRoutes;
using ShardingCore.Helpers;
using ShardingCore.Test.Common;
using ShardingCore.Test.Domain.Entities;
using ShardingCore.VirtualRoutes.Months;
namespace ShardingCore.Test.Shardings
{
public class MultiShardingOrderVirtualTableRoute:AbstractSimpleShardingMonthKeyDateTimeVirtualTableRoute<MultiShardingOrder>
{
public override void Configure(EntityMetadataTableBuilder<MultiShardingOrder> builder)
{
builder.ShardingProperty(o => o.CreateTime);
builder.ShardingExtraProperty(o => o.Id);
}
public override Func<string, bool> GetExtraRouteFilter(object shardingKey, ShardingOperatorEnum shardingOperator, string shardingPropertyName)
{
switch (shardingPropertyName)
{
case nameof(MultiShardingOrder.Id): return GetIdRouteFilter(shardingKey, shardingOperator);
default: throw new NotImplementedException(shardingPropertyName);
}
}
private Func<string, bool> GetIdRouteFilter(object shardingKey,
ShardingOperatorEnum shardingOperator)
{
//解析雪花id 需要考虑异常情况,传入的可能不是雪花id那么可以随机查询一张表
var analyzeIdToDateTime = SnowflakeId.AnalyzeIdToDateTime(Convert.ToInt64(shardingKey));
//当前时间的tail
var t = TimeFormatToTail(analyzeIdToDateTime);
//因为是按月分表所以获取下个月的时间判断id是否是在灵界点创建的
var nextMonthFirstDay = ShardingCoreHelper.GetNextMonthFirstDay(DateTime.Now);
if (analyzeIdToDateTime.AddSeconds(10) > nextMonthFirstDay)
{
var nextT = TimeFormatToTail(nextMonthFirstDay);
if (shardingOperator == ShardingOperatorEnum.Equal)
{
return tail => tail == t||tail== nextT;
}
}
var currentMonthFirstDay = ShardingCoreHelper.GetCurrentMonthFirstDay(DateTime.Now);
if (analyzeIdToDateTime.AddSeconds(-10) < currentMonthFirstDay)
{
//上个月tail
var nextT = TimeFormatToTail(analyzeIdToDateTime.AddSeconds(-10));
if (shardingOperator == ShardingOperatorEnum.Equal)
{
return tail => tail == t || tail == nextT;
}
}
else
{
if (shardingOperator == ShardingOperatorEnum.Equal)
{
return tail => tail == t;
}
}
return tail => true;
}
public override bool AutoCreateTableByTime()
{
return true;
}
public override DateTime GetBeginTime()
{
return new DateTime(2021, 9, 1);
}
}
}

View File

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Core.VirtualRoutes;
using ShardingCore.Core.VirtualRoutes.DataSourceRoutes.Abstractions;
using ShardingCore.Test.Domain.Entities;
namespace ShardingCore.Test.Shardings
{
public class OrderAreaShardingVirtualDataSourceRoute:AbstractShardingOperatorVirtualDataSourceRoute<Order,string>
{
//public override bool? EnableRouteParseCompileCache => true;
protected override bool EnableHintRoute =>true;
private readonly List<string> _dataSources = new List<string>()
{
"A", "B", "C"
};
//我们设置区域就是数据库
public override string ShardingKeyToDataSourceName(object shardingKey)
{
return shardingKey?.ToString() ?? string.Empty;
}
public override List<string> GetAllDataSourceNames()
{
return _dataSources;
}
public override bool AddDataSourceName(string dataSourceName)
{
if (_dataSources.Any(o => o == dataSourceName))
return false;
_dataSources.Add(dataSourceName);
return true;
}
public override void Configure(EntityMetadataDataSourceBuilder<Order> builder)
{
builder.ShardingProperty(o => o.Area);
}
public override 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;
}
}
}
}
}

View File

@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Sharding.PaginationConfigurations;
using ShardingCore.Test.Domain.Entities;
using ShardingCore.VirtualRoutes.Months;
namespace ShardingCore.Test.Shardings
{
public class OrderCreateTimeVirtualTableRoute:AbstractSimpleShardingMonthKeyDateTimeVirtualTableRoute<Order>
{
//public override bool? EnableRouteParseCompileCache => true;
public override DateTime GetBeginTime()
{
return new DateTime(2021, 1, 1);
}
protected override List<string> CalcTailsOnStart()
{
var allTails = base.CalcTailsOnStart();
allTails.Add("202112");
return allTails;
}
public override void Configure(EntityMetadataTableBuilder<Order> builder)
{
builder.ShardingProperty(o => o.CreateTime);
}
public override IPaginationConfiguration<Order> CreatePaginationConfiguration()
{
return new OrderCreateTimePaginationConfiguration();
}
public override bool AutoCreateTableByTime()
{
return true;
}
}
//public class HistoryMinCompare : IComparer<string>
//{
// private const string History = "History";
// public int Compare(string? x, string? y)
// {
// if (!Object.Equals(x, y))
// {
// if (History.Equals(x))
// return -1;
// if (History.Equals(y))
// return 1;
// }
// return Comparer<string>.Default.Compare(x, y);
// }
//}
public class OrderCreateTimePaginationConfiguration : IPaginationConfiguration<Order>
{
public void Configure(PaginationBuilder<Order> builder)
{
builder.PaginationSequence(o => o.CreateTime)
.UseQueryMatch(PaginationMatchEnum.Owner | PaginationMatchEnum.Named | PaginationMatchEnum.PrimaryMatch)
.UseAppendIfOrderNone().UseRouteComparer(Comparer<string>.Default);
}
}
}

View File

@ -0,0 +1,15 @@
using ShardingCore.Sharding.PaginationConfigurations;
using ShardingCore.Test.Domain.Entities;
namespace ShardingCore.Test.Shardings.PaginationConfigs
{
public class LogDayPaginationConfiguration: IPaginationConfiguration<LogDay>
{
public void Configure(PaginationBuilder<LogDay> builder)
{
builder.PaginationSequence(o => o.LogTime)
.UseQueryMatch(PaginationMatchEnum.Named | PaginationMatchEnum.Owner |
PaginationMatchEnum.PrimaryMatch).UseAppendIfOrderNone();
}
}
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Test.Domain.Entities;
using ShardingCore.VirtualRoutes.Mods;
namespace ShardingCore.Test.Shardings
{
public class SysUserModIntVirtualRoute:AbstractSimpleShardingModKeyIntVirtualTableRoute<SysUserModInt>
{
protected override bool EnableHintRoute => true;
//public override bool? EnableRouteParseCompileCache => true;
public SysUserModIntVirtualRoute() : base(2, 3)
{
}
public override void Configure(EntityMetadataTableBuilder<SysUserModInt> builder)
{
builder.ShardingProperty(o => o.Id);
}
}
}

View File

@ -0,0 +1,28 @@
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Test.Domain.Entities;
using ShardingCore.VirtualRoutes.Mods;
namespace ShardingCore.Test.Shardings
{
/*
* @Author: xjm
* @Description:
* @Date: Thursday, 14 January 2021 15:39:27
* @Email: 326308290@qq.com
*/
public class SysUserModVirtualTableRoute : AbstractSimpleShardingModKeyStringVirtualTableRoute<SysUserMod>
{
protected override bool EnableHintRoute => true;
//public override bool? EnableRouteParseCompileCache => true;
public SysUserModVirtualTableRoute() : base(2,3)
{
}
public override void Configure(EntityMetadataTableBuilder<SysUserMod> builder)
{
builder.ShardingProperty(o => o.Id);
builder.TableSeparator("_");
}
}
}

View File

@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Core.VirtualRoutes;
using ShardingCore.Core.VirtualRoutes.TableRoutes.Abstractions;
using ShardingCore.Test.Domain.Entities;
namespace ShardingCore.Test.Shardings
{
/*
* @Author: xjm
* @Description:
* @Date: Monday, 01 February 2021 15:54:55
* @Email: 326308290@qq.com
*/
public class SysUserSalaryVirtualTableRoute:AbstractShardingOperatorVirtualTableRoute<SysUserSalary,int>
{
//public override bool? EnableRouteParseCompileCache => true;
protected override bool EnableHintRoute => true;
public override string ShardingKeyToTail(object shardingKey)
{
var time = Convert.ToInt32(shardingKey);
return TimeFormatToTail(time);
}
public override List<string> GetTails()
{
var beginTime = new DateTime(2020, 1, 1);
var endTime = new DateTime(2021, 12, 1);
var list = new List<string>(24);
var tempTime = beginTime;
while (tempTime <= endTime)
{
list.Add($"{tempTime:yyyyMM}");
tempTime = tempTime.AddMonths(1);
}
return list;
}
protected string TimeFormatToTail(int time)
{
var dateOfMonth=DateTime.ParseExact($"{time}","yyyyMM",System.Globalization.CultureInfo.InvariantCulture,System.Globalization.DateTimeStyles.AdjustToUniversal);
return $"{dateOfMonth:yyyyMM}";
}
public override Func<string, bool> GetRouteToFilter(int shardingKey, ShardingOperatorEnum shardingOperator)
{
var t = TimeFormatToTail(shardingKey);
switch (shardingOperator)
{
case ShardingOperatorEnum.GreaterThan:
case ShardingOperatorEnum.GreaterThanOrEqual:
return tail => String.Compare(tail, t, StringComparison.Ordinal) >= 0;
case ShardingOperatorEnum.LessThan:
return tail => String.Compare(tail, t, StringComparison.Ordinal) < 0;
case ShardingOperatorEnum.LessThanOrEqual:
return tail => String.Compare(tail, t, StringComparison.Ordinal) <= 0;
case ShardingOperatorEnum.Equal: return tail => tail == t;
default:
{
#if DEBUG
Console.WriteLine($"shardingOperator is not equal scan all table tail");
#endif
return tail => true;
}
}
}
public override void Configure(EntityMetadataTableBuilder<SysUserSalary> builder)
{
builder.ShardingProperty(o => o.DateOfMonth);
}
}
}

View File

@ -0,0 +1,383 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ShardingCore.Bootstrappers;
using ShardingCore.Core;
using ShardingCore.Helpers;
using ShardingCore.Sharding.ReadWriteConfigurations;
using ShardingCore.TableExists;
using ShardingCore.TableExists.Abstractions;
using ShardingCore.Test.Domain.Entities;
using ShardingCore.Test.Shardings;
namespace ShardingCore.Test
{
/*
* @Author: xjm
* @Description:
* @Date: Friday, 15 January 2021 15:37:46
* @Email: 326308290@qq.com
*/
public class Startup
{
public static readonly ILoggerFactory efLogger = LoggerFactory.Create(builder =>
{
builder.AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information).AddConsole();
});
// 支持的形式:
// ConfigureServices(IServiceCollection services)
// ConfigureServices(IServiceCollection services, HostBuilderContext hostBuilderContext)
// ConfigureServices(HostBuilderContext hostBuilderContext, IServiceCollection services)
public void ConfigureServices(IServiceCollection services, HostBuilderContext hostBuilderContext)
{
services.AddShardingDbContext<ShardingDefaultDbContext>()
.UseRouteConfig(op =>
{
op.AddShardingDataSourceRoute<OrderAreaShardingVirtualDataSourceRoute>();
op.AddShardingTableRoute<SysUserModVirtualTableRoute>();
op.AddShardingTableRoute<SysUserSalaryVirtualTableRoute>();
op.AddShardingTableRoute<OrderCreateTimeVirtualTableRoute>();
op.AddShardingTableRoute<LogDayVirtualTableRoute>();
op.AddShardingTableRoute<LogWeekDateTimeVirtualTableRoute>();
op.AddShardingTableRoute<LogWeekTimeLongVirtualTableRoute>();
op.AddShardingTableRoute<LogYearDateTimeVirtualRoute>();
op.AddShardingTableRoute<LogMonthLongvirtualRoute>();
op.AddShardingTableRoute<LogYearLongVirtualRoute>();
op.AddShardingTableRoute<SysUserModIntVirtualRoute>();
op.AddShardingTableRoute<LogDayLongVirtualRoute>();
op.AddShardingTableRoute<MultiShardingOrderVirtualTableRoute>();
})
.UseConfig(op =>
{
op.AutoUseWriteConnectionStringAfterWriteDb = true;
op.CacheModelLockConcurrencyLevel = Environment.ProcessorCount;
//op.UseEntityFrameworkCoreProxies = true;
//当无法获取路由时会返回默认值而不是报错
op.ThrowIfQueryRouteNotMatch = false;
//忽略建表错误compensate table和table creator
op.IgnoreCreateTableError = true;
//迁移时使用的并行线程数(分库有效)defaultShardingDbContext.Database.Migrate()
op.MigrationParallelCount = Environment.ProcessorCount;
//补偿表创建并行线程数 调用UseAutoTryCompensateTable有效
op.CompensateTableParallelCount = Environment.ProcessorCount;
//最大连接数限制
op.MaxQueryConnectionsLimit = Environment.ProcessorCount;
//链接模式系统默认
op.ConnectionMode = ConnectionModeEnum.SYSTEM_AUTO;
//如何通过字符串查询创建DbContext
op.UseShardingQuery((conStr, builder) =>
{
builder.UseSqlServer(conStr).UseLoggerFactory(efLogger);
});
//如何通过事务创建DbContext
op.UseShardingTransaction((connection, builder) =>
{
builder.UseSqlServer(connection).UseLoggerFactory(efLogger);
});
//添加默认数据源
op.AddDefaultDataSource("A",
"Data Source=localhost;Initial Catalog=ShardingCoreDBA;Integrated Security=True;TrustServerCertificate=True;");
//添加额外数据源
op.AddExtraDataSource(sp =>
{
return new Dictionary<string, string>()
{
{ "B", "Data Source=localhost;Initial Catalog=ShardingCoreDBB;Integrated Security=True;TrustServerCertificate=True;" },
{ "C", "Data Source=localhost;Initial Catalog=ShardingCoreDBC;Integrated Security=True;TrustServerCertificate=True;" },
};
});
//添加读写分离
op.AddReadWriteSeparation(sp =>
{
return new Dictionary<string, IEnumerable<string>>()
{
{
"A", new HashSet<string>()
{
"Data Source=localhost;Initial Catalog=ShardingCoreDBB;Integrated Security=True;TrustServerCertificate=True;"
}
}
};
}, ReadStrategyEnum.Loop, defaultEnable: false, readConnStringGetStrategy: ReadConnStringGetStrategyEnum.LatestEveryTime);
})
.AddShardingCore();
}
// 可以添加要用到的方法参数,会自动从注册的服务中获取服务实例,类似于 asp.net core 里 Configure 方法
public void Configure(IServiceProvider serviceProvider)
{
//启动ShardingCore创建表任务
//启动进行表补偿
serviceProvider.UseAutoTryCompensateTable();
// 有一些测试数据要初始化可以放在这里
InitData(serviceProvider).GetAwaiter().GetResult();
}
/// <summary>
/// 添加种子数据
/// </summary>
/// <param name="serviceProvider"></param>
/// <returns></returns>
private async Task InitData(IServiceProvider serviceProvider)
{
using (var scope = serviceProvider.CreateScope())
{
var virtualDbContext = scope.ServiceProvider.GetService<ShardingDefaultDbContext>();
if (!await virtualDbContext.Set<SysUserMod>().AnyAsync())
{
var ids = Enumerable.Range(1, 1000);
var userMods = new List<SysUserMod>();
var userModInts = new List<SysUserModInt>();
var userSalaries = new List<SysUserSalary>();
var beginTime = new DateTime(2020, 1, 1);
var endTime = new DateTime(2021, 12, 1);
foreach (var id in ids)
{
userMods.Add(new SysUserMod()
{
Id = id.ToString(),
Age = id,
Name = $"name_{id}",
AgeGroup = Math.Abs(id % 10)
});
userModInts.Add(new SysUserModInt()
{
Id = id,
Age = id,
Name = $"name_{id}",
AgeGroup = Math.Abs(id % 10)
});
var tempTime = beginTime;
var i = 0;
while (tempTime <= endTime)
{
var dateOfMonth = $@"{tempTime:yyyyMM}";
userSalaries.Add(new SysUserSalary()
{
Id = $@"{id}{dateOfMonth}",
UserId = id.ToString(),
DateOfMonth = int.Parse(dateOfMonth),
Salary = 700000 + id * 100 * i,
SalaryLong = 700000 + id * 100 * i,
SalaryDecimal = (700000 + id * 100 * i) / 100m,
SalaryDouble = (700000 + id * 100 * i) / 100d,
SalaryFloat = (700000 + id * 100 * i) / 100f
});
tempTime = tempTime.AddMonths(1);
i++;
}
}
var areas = new List<string>(){"A","B","C"};
List<Order> orders = new List<Order>(360);
var begin = new DateTime(2021, 1, 1);
for (int i = 0; i < 320; i++)
{
orders.Add(new Order()
{
Id = Guid.NewGuid(),
Area = areas[i%3],
CreateTime = begin,
Money = i
});
begin = begin.AddDays(1);
}
List<LogDay> logDays = new List<LogDay>(3600);
List<LogDayLong> logDayLongs = new List<LogDayLong>(3600);
var levels = new List<string>(){"info","warning","error"};
var begin1 = new DateTime(2021, 1, 1);
for (int i = 0; i < 300; i++)
{
var ltime = begin1;
for (int j = 0; j < 10; j++)
{
logDays.Add(new LogDay()
{
Id = Guid.NewGuid(),
LogLevel = levels[j%3],
LogBody = $"{i}_{j}",
LogTime = ltime.AddHours(1)
});
logDayLongs.Add(new LogDayLong()
{
Id = Guid.NewGuid(),
LogLevel = levels[j%3],
LogBody = $"{i}_{j}",
LogTime = ShardingCoreHelper.ConvertDateTimeToLong(ltime.AddHours(1))
});
ltime = ltime.AddHours(1);
}
begin1 = begin1.AddDays(1);
}
List<LogWeekDateTime> logWeeks = new List<LogWeekDateTime>(300);
var begin2 = new DateTime(2021,1,1);
for (int i = 0; i < 300; i++)
{
logWeeks.Add(new LogWeekDateTime()
{
Id = Guid.NewGuid().ToString("n"),
Body = $"body_{i}",
LogTime = begin2
});
begin2 = begin2.AddDays(1);
}
List<LogWeekTimeLong> logWeekLongs = new List<LogWeekTimeLong>(300);
var begin3 = new DateTime(2021,1,1);
for (int i = 0; i < 300; i++)
{
logWeekLongs.Add(new LogWeekTimeLong()
{
Id = Guid.NewGuid().ToString("n"),
Body = $"body_{i}",
LogTime = ShardingCoreHelper.ConvertDateTimeToLong(begin3)
});
begin3 = begin3.AddDays(1);
}
List<LogYearDateTime> logYears = new List<LogYearDateTime>(600);
var begin4 = new DateTime(2020,1,1);
for (int i = 0; i < 600; i++)
{
logYears.Add(new LogYearDateTime()
{
Id = Guid.NewGuid(),
LogBody = $"body_{i}",
LogTime = begin4
});
begin4 = begin4.AddDays(1);
}
List<LogMonthLong> logMonthLongs = new List<LogMonthLong>(300);
var begin5 = new DateTime(2021, 1, 1);
for (int i = 0; i < 300; i++)
{
logMonthLongs.Add(new LogMonthLong()
{
Id = Guid.NewGuid().ToString("n"),
Body = $"body_{i}",
LogTime = ShardingCoreHelper.ConvertDateTimeToLong(begin5)
});
begin5 = begin5.AddDays(1);
}
List<LogYearLong> logYearkLongs = new List<LogYearLong>(300);
var begin6 = new DateTime(2021, 1, 1);
for (int i = 0; i < 300; i++)
{
logYearkLongs.Add(new LogYearLong()
{
Id = Guid.NewGuid().ToString("n"),
LogBody = $"body_{i}",
LogTime = ShardingCoreHelper.ConvertDateTimeToLong(begin6)
});
begin6 = begin6.AddDays(1);
}
var multiShardingOrders = new List<MultiShardingOrder>(9);
#region
{
var now = new DateTime(2021, 10, 1, 13, 13, 11);
multiShardingOrders.Add(new MultiShardingOrder()
{
Id = 231765457240207360,
Name = $"{now:yyyy/MM/dd HH:mm:ss}",
CreateTime = now
});
}
{
var now = new DateTime(2021, 10, 2, 11, 3, 11);
multiShardingOrders.Add(new MultiShardingOrder()
{
Id = 232095129534607360,
Name = $"{now:yyyy/MM/dd HH:mm:ss}",
CreateTime = now
});
}
{
var now = new DateTime(2021, 10, 3, 7, 7, 7);
multiShardingOrders.Add(new MultiShardingOrder()
{
Id = 232398109278351360,
Name = $"{now:yyyy/MM/dd HH:mm:ss}",
CreateTime = now
});
}
{
var now = new DateTime(2021, 11, 6, 13, 13, 11);
multiShardingOrders.Add(new MultiShardingOrder()
{
Id = 244811420401807360,
Name = $"{now:yyyy/MM/dd HH:mm:ss}",
CreateTime = now
});
}
{
var now = new DateTime(2021, 11, 21, 19, 43, 0);
multiShardingOrders.Add(new MultiShardingOrder()
{
Id = 250345338962063360,
Name = $"{now:yyyy/MM/dd HH:mm:ss}",
CreateTime = now
});
}
{
var now = new DateTime(2021, 12, 5, 5, 5, 11);
multiShardingOrders.Add(new MultiShardingOrder()
{
Id = 255197859283087360,
Name = $"{now:yyyy/MM/dd HH:mm:ss}",
CreateTime = now
});
}
{
var now = new DateTime(2021, 12, 9, 19, 13, 11);
multiShardingOrders.Add(new MultiShardingOrder()
{
Id = 256860816933007360,
Name = $"{now:yyyy/MM/dd HH:mm:ss}",
CreateTime = now
});
}
{
var now = new DateTime(2021, 12, 19, 13, 13, 11);
multiShardingOrders.Add(new MultiShardingOrder()
{
Id = 260394098622607360,
Name = $"{now:yyyy/MM/dd HH:mm:ss}",
CreateTime = now
});
}
#endregion
using (var tran = virtualDbContext.Database.BeginTransaction())
{
await virtualDbContext.AddRangeAsync(userMods);
await virtualDbContext.AddRangeAsync(userModInts);
await virtualDbContext.AddRangeAsync(userSalaries);
await virtualDbContext.AddRangeAsync(orders);
await virtualDbContext.AddRangeAsync(logDays);
await virtualDbContext.AddRangeAsync(logDayLongs);
await virtualDbContext.AddRangeAsync(logWeeks);
await virtualDbContext.AddRangeAsync(logWeekLongs);
await virtualDbContext.AddRangeAsync(logYears);
await virtualDbContext.AddRangeAsync(logMonthLongs);
await virtualDbContext.AddRangeAsync(logYearkLongs);
await virtualDbContext.AddRangeAsync(multiShardingOrders);
await virtualDbContext.SaveChangesAsync();
tran.Commit();
}
}
}
}
}
}

View File

@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net6.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>

View File

@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net6.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<DefineConstants>TRACE;DEBUG;EFCORE6Test;</DefineConstants> <DefineConstants>TRACE;DEBUG;EFCORE6Test;</DefineConstants>
<AssemblyName>ShardingCore.Test</AssemblyName> <AssemblyName>ShardingCore.Test</AssemblyName>
<LangVersion>latest</LangVersion> <LangVersion>latest</LangVersion>
@ -9,8 +9,8 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="6.0.9" /> <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="6.0.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="7.0.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="8.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.0" />
<PackageReference Include="xunit" Version="2.4.2" /> <PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="Xunit.DependencyInjection" Version="8.5.0" /> <PackageReference Include="Xunit.DependencyInjection" Version="8.5.0" />

View File

@ -74,12 +74,12 @@ namespace ShardingCore.Test
//如何通过字符串查询创建DbContext //如何通过字符串查询创建DbContext
op.UseShardingQuery((conStr, builder) => op.UseShardingQuery((conStr, builder) =>
{ {
builder.UseSqlServer(conStr).UseLoggerFactory(efLogger); builder.UseSqlServer(conStr, o => o.UseCompatibilityLevel(120)).UseLoggerFactory(efLogger);
}); });
//如何通过事务创建DbContext //如何通过事务创建DbContext
op.UseShardingTransaction((connection, builder) => op.UseShardingTransaction((connection, builder) =>
{ {
builder.UseSqlServer(connection).UseLoggerFactory(efLogger); builder.UseSqlServer(connection, o => o.UseCompatibilityLevel(120)).UseLoggerFactory(efLogger);
}); });
//添加默认数据源 //添加默认数据源
op.AddDefaultDataSource("A", op.AddDefaultDataSource("A",