Skip to content

Commit afef8e7

Browse files
committed
仅分库track
1 parent 4f31e8f commit afef8e7

File tree

16 files changed

+342
-25
lines changed

16 files changed

+342
-25
lines changed

ShardingCore.sln

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ShardingCore3", "src3\Shard
7373
EndProject
7474
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ShardingCore2", "src2\ShardingCore2\ShardingCore2.csproj", "{F0393C32-2285-4F47-AC61-C1BA1CAC269D}"
7575
EndProject
76+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample.MySQLDataSourceOnly", "samples\Sample.MySQLDataSourceOnly\Sample.MySQLDataSourceOnly.csproj", "{3B5A4B03-5190-41A8-8E4B-F95A79A5C018}"
77+
EndProject
7678
Global
7779
GlobalSection(SolutionConfigurationPlatforms) = preSolution
7880
Debug|Any CPU = Debug|Any CPU
@@ -187,6 +189,10 @@ Global
187189
{F0393C32-2285-4F47-AC61-C1BA1CAC269D}.Debug|Any CPU.Build.0 = Debug|Any CPU
188190
{F0393C32-2285-4F47-AC61-C1BA1CAC269D}.Release|Any CPU.ActiveCfg = Release|Any CPU
189191
{F0393C32-2285-4F47-AC61-C1BA1CAC269D}.Release|Any CPU.Build.0 = Release|Any CPU
192+
{3B5A4B03-5190-41A8-8E4B-F95A79A5C018}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
193+
{3B5A4B03-5190-41A8-8E4B-F95A79A5C018}.Debug|Any CPU.Build.0 = Debug|Any CPU
194+
{3B5A4B03-5190-41A8-8E4B-F95A79A5C018}.Release|Any CPU.ActiveCfg = Release|Any CPU
195+
{3B5A4B03-5190-41A8-8E4B-F95A79A5C018}.Release|Any CPU.Build.0 = Release|Any CPU
190196
EndGlobalSection
191197
GlobalSection(SolutionProperties) = preSolution
192198
HideSolutionNode = FALSE
@@ -219,6 +225,7 @@ Global
219225
{E5E48D52-CAD3-42F0-82CD-A2A6180F3C4D} = {53D07876-A791-46AE-8381-08557593693D}
220226
{B59909AD-8885-40F3-9454-6C8433463BCC} = {51E1D067-3E81-4815-94F2-F8ABBE80881E}
221227
{F0393C32-2285-4F47-AC61-C1BA1CAC269D} = {B11D7DF7-A907-407E-8BF1-35B430413557}
228+
{3B5A4B03-5190-41A8-8E4B-F95A79A5C018} = {EDF8869A-C1E1-491B-BC9F-4A33F4DE1C73}
222229
EndGlobalSection
223230
GlobalSection(ExtensibilityGlobals) = postSolution
224231
SolutionGuid = {8C07A667-E8B4-43C7-8053-721584BAD291}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
using Microsoft.AspNetCore.Mvc;
2+
using Sample.MySQLDataSourceOnly.Domain;
3+
4+
namespace Sample.MySQLDataSourceOnly.Controllers;
5+
6+
[ApiController]
7+
[Route("[controller]")]
8+
public class WeatherForecastController : ControllerBase
9+
{
10+
private static readonly string[] Summaries = new[]
11+
{
12+
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
13+
};
14+
15+
private readonly ILogger<WeatherForecastController> _logger;
16+
private readonly MyDbContext _myDbContext;
17+
18+
public WeatherForecastController(ILogger<WeatherForecastController> logger,MyDbContext myDbContext)
19+
{
20+
_logger = logger;
21+
_myDbContext = myDbContext;
22+
}
23+
24+
[HttpGet(Name = "GetWeatherForecast")]
25+
public IEnumerable<WeatherForecast> Get()
26+
{
27+
var user = _myDbContext.Set<SysUser>().FirstOrDefault(o=>o.Id=="1");
28+
user.Name = "456"+DateTime.Now.ToString();
29+
_myDbContext.SaveChanges();
30+
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
31+
{
32+
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
33+
TemperatureC = Random.Shared.Next(-20, 55),
34+
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
35+
})
36+
.ToArray();
37+
}
38+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
using Microsoft.EntityFrameworkCore;
2+
using ShardingCore.Sharding;
3+
4+
namespace Sample.MySQLDataSourceOnly.Domain;
5+
6+
7+
public class MyDbContext : AbstractShardingDbContext
8+
{
9+
public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
10+
{
11+
}
12+
13+
protected override void OnModelCreating(ModelBuilder modelBuilder)
14+
{
15+
base.OnModelCreating(modelBuilder);
16+
modelBuilder.Entity<SysUser>(entity =>
17+
{
18+
entity.HasKey(o => o.Id);
19+
entity.Property(o => o.Id).IsRequired().IsUnicode(false).HasMaxLength(50);
20+
entity.Property(o => o.Name).IsRequired().IsUnicode(false).HasMaxLength(50);
21+
entity.Property(o => o.Area).IsRequired().IsUnicode(false).HasMaxLength(50);
22+
entity.ToTable(nameof(SysUser));
23+
});
24+
}
25+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
namespace Sample.MySQLDataSourceOnly.Domain;
2+
3+
public class SysUser
4+
{
5+
public string Id { get; set; }
6+
public string Name { get; set; }
7+
public string Area { get; set; }
8+
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
using ShardingCore.Core.EntityMetadatas;
2+
using ShardingCore.Core.VirtualRoutes;
3+
using ShardingCore.Core.VirtualRoutes.DataSourceRoutes.Abstractions;
4+
5+
namespace Sample.MySQLDataSourceOnly.Domain;
6+
7+
public class SysUserVirtualDataSourceRoute : AbstractShardingOperatorVirtualDataSourceRoute<SysUser, string>
8+
{
9+
private readonly List<string> _dataSources = new List<string>()
10+
{
11+
"A", "B", "C"
12+
};
13+
protected string ConvertToShardingKey(object shardingKey)
14+
{
15+
return shardingKey?.ToString() ?? string.Empty;
16+
}
17+
18+
//我们设置区域就是数据库
19+
public override string ShardingKeyToDataSourceName(object shardingKey)
20+
{
21+
return ConvertToShardingKey(shardingKey);
22+
}
23+
24+
public override List<string> GetAllDataSourceNames()
25+
{
26+
return _dataSources;
27+
}
28+
29+
public override bool AddDataSourceName(string dataSourceName)
30+
{
31+
if (_dataSources.Any(o => o == dataSourceName))
32+
return false;
33+
_dataSources.Add(dataSourceName);
34+
return true;
35+
}
36+
37+
public override Func<string, bool> GetRouteToFilter(string shardingKey, ShardingOperatorEnum shardingOperator)
38+
{
39+
40+
var t = ShardingKeyToDataSourceName(shardingKey);
41+
switch (shardingOperator)
42+
{
43+
case ShardingOperatorEnum.Equal: return tail => tail == t;
44+
default:
45+
{
46+
return tail => true;
47+
}
48+
}
49+
}
50+
51+
public override void Configure(EntityMetadataDataSourceBuilder<SysUser> builder)
52+
{
53+
builder.ShardingProperty(o => o.Area);
54+
}
55+
}
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
using Microsoft.EntityFrameworkCore;
2+
using Sample.MySQLDataSourceOnly.Domain;
3+
using ShardingCore;
4+
5+
var builder = WebApplication.CreateBuilder(args);
6+
7+
// Add services to the container.
8+
9+
builder.Services.AddControllers();
10+
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
11+
builder.Services.AddEndpointsApiExplorer();
12+
builder.Services.AddSwaggerGen();
13+
14+
15+
16+
builder.Services.AddShardingDbContext<MyDbContext>()
17+
.UseRouteConfig(o =>
18+
{
19+
//o.CreateShardingTableOnStart = true;
20+
//o.EnsureCreatedWithOutShardingTable = true;
21+
o.AddShardingDataSourceRoute<SysUserVirtualDataSourceRoute>();
22+
})
23+
.UseConfig((sp,op) =>
24+
{
25+
var loggerFactory = sp.ApplicationServiceProvider.GetService<ILoggerFactory>();
26+
//op.ConfigId = "c1";
27+
op.UseShardingQuery((conStr, builder) =>
28+
{
29+
builder.UseMySql(conStr,new MySqlServerVersion(new Version()))
30+
.UseLoggerFactory(loggerFactory).EnableSensitiveDataLogging();
31+
});
32+
op.UseShardingTransaction((connection, builder) =>
33+
{
34+
builder.UseMySql(connection,new MySqlServerVersion(new Version()))
35+
.UseLoggerFactory(loggerFactory).EnableSensitiveDataLogging();;
36+
});
37+
//op.ReplaceTableEnsureManager(sp => new SqlServerTableEnsureManager<MyDbContext>());
38+
op.AddDefaultDataSource("A", @"server=127.0.0.1;port=3306;database=onlyds1;userid=root;password=root;");
39+
op.AddExtraDataSource(sp =>
40+
{
41+
return new Dictionary<string, string>()
42+
{
43+
{
44+
"B",
45+
@"server=127.0.0.1;port=3306;database=onlyds2;userid=root;password=root;"
46+
},
47+
{
48+
"C",
49+
@"server=127.0.0.1;port=3306;database=onlyds3;userid=root;password=root;"
50+
},
51+
};
52+
});
53+
}).AddShardingCore();
54+
55+
var app = builder.Build();
56+
57+
// Configure the HTTP request pipeline.
58+
if (app.Environment.IsDevelopment())
59+
{
60+
app.UseSwagger();
61+
app.UseSwaggerUI();
62+
}
63+
64+
app.UseHttpsRedirection();
65+
66+
app.UseAuthorization();
67+
68+
app.MapControllers();
69+
app.Services.UseAutoTryCompensateTable();
70+
// using (var serviceScope = app.Services.CreateScope())
71+
// {
72+
// var myDbContext = serviceScope.ServiceProvider.GetService<MyDbContext>();
73+
// myDbContext.Database.EnsureCreated();
74+
// myDbContext.Add(new SysUser() { Id = "1", Area = "A", Name = "name" });
75+
// myDbContext.SaveChanges();
76+
// }
77+
app.Run();
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
{
2+
"$schema": "https://json.schemastore.org/launchsettings.json",
3+
"iisSettings": {
4+
"windowsAuthentication": false,
5+
"anonymousAuthentication": true,
6+
"iisExpress": {
7+
"applicationUrl": "http://localhost:35669",
8+
"sslPort": 44323
9+
}
10+
},
11+
"profiles": {
12+
"http": {
13+
"commandName": "Project",
14+
"dotnetRunMessages": true,
15+
"launchBrowser": true,
16+
"launchUrl": "swagger",
17+
"applicationUrl": "http://localhost:5029",
18+
"environmentVariables": {
19+
"ASPNETCORE_ENVIRONMENT": "Development"
20+
}
21+
},
22+
"https": {
23+
"commandName": "Project",
24+
"dotnetRunMessages": true,
25+
"launchBrowser": true,
26+
"launchUrl": "swagger",
27+
"applicationUrl": "https://localhost:7187;http://localhost:5029",
28+
"environmentVariables": {
29+
"ASPNETCORE_ENVIRONMENT": "Development"
30+
}
31+
},
32+
"IIS Express": {
33+
"commandName": "IISExpress",
34+
"launchBrowser": true,
35+
"launchUrl": "swagger",
36+
"environmentVariables": {
37+
"ASPNETCORE_ENVIRONMENT": "Development"
38+
}
39+
}
40+
}
41+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
3+
<PropertyGroup>
4+
<TargetFramework>net7.0</TargetFramework>
5+
<Nullable>enable</Nullable>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
</PropertyGroup>
8+
9+
<ItemGroup>
10+
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.0" />
11+
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="7.0.0" />
12+
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
13+
</ItemGroup>
14+
15+
<ItemGroup>
16+
<ProjectReference Include="..\..\src\ShardingCore\ShardingCore.csproj" />
17+
</ItemGroup>
18+
19+
</Project>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
namespace Sample.MySQLDataSourceOnly;
2+
3+
public class WeatherForecast
4+
{
5+
public DateOnly Date { get; set; }
6+
7+
public int TemperatureC { get; set; }
8+
9+
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
10+
11+
public string? Summary { get; set; }
12+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"Logging": {
3+
"LogLevel": {
4+
"Default": "Information",
5+
"Microsoft.AspNetCore": "Warning"
6+
}
7+
}
8+
}

0 commit comments

Comments
 (0)