Skip to content

Commit

Permalink
读写分离添加默认行为方式
Browse files Browse the repository at this point in the history
  • Loading branch information
xuejmnet committed May 11, 2023
1 parent 9ae39a5 commit 13c76f4
Show file tree
Hide file tree
Showing 24 changed files with 229 additions and 34 deletions.
36 changes: 36 additions & 0 deletions samples/Sample.MySql/Controllers/WeatherForecastController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -318,5 +318,41 @@ public async Task<IActionResult> Get8()
// var sysUserMods2 = await _defaultTableDbContext.Set<SysTest>().FromSqlRaw("select * from SysTest where id='2'").ToListAsync();
return Ok();
}
[HttpGet]
public async Task<IActionResult> Get9()
{
var sysUserMod = await _defaultTableDbContext.Set<SysUserMod>().Where(o=>o.Name=="11231").AllAsync(o=>o.Id=="1123");

// var sysUserMods1 = await _defaultTableDbContext.Set<SysUserMod>().FromSqlRaw("select * from SysUserMod where id='2'").ToListAsync();
// var sysUserMods2 = await _defaultTableDbContext.Set<SysTest>().FromSqlRaw("select * from SysTest where id='2'").ToListAsync();
return Ok();
}
[HttpGet]
public async Task<IActionResult> Get10()
{
var sysUserMod1 = await _defaultTableDbContext.Set<SysTest>().Where(o=>o.UserId=="11231").AllAsync(o=>o.Id=="1123"&&string.Compare(o.UserId,"123")>0);
var sysUserMod2 = await _defaultTableDbContext.Set<SysTest>().AllAsync(o=>o.Id=="1123");
var dateTime = new DateTime(2020,1,1);
var sysUserMod3 = await _defaultTableDbContext.Set<SysUserLogByMonth>().Where(o => o.Time > dateTime)
.ToListAsync();

// var sysUserMods1 = await _defaultTableDbContext.Set<SysUserMod>().FromSqlRaw("select * from SysUserMod where id='2'").ToListAsync();
// var sysUserMods2 = await _defaultTableDbContext.Set<SysTest>().FromSqlRaw("select * from SysTest where id='2'").ToListAsync();
return Ok();
}
[HttpGet]
public async Task<IActionResult> Get11()
{
using(var tran = await _defaultTableDbContext.Database.BeginTransactionAsync())
{
var newGuid = Guid.NewGuid().ToString("n");
await _defaultTableDbContext.Set<SysTest>().Where(o => o.Id == "11")
.ExecuteUpdateAsync(o => o.SetProperty(x => x.UserId, x => newGuid));
throw new Exception("123");
await tran.CommitAsync();
}

return Ok();
}
}
}
6 changes: 5 additions & 1 deletion samples/Sample.MySql/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
// app.ApplicationServices.UseAutoTryCompensateTable();
// using (var scope = app.ApplicationServices.CreateScope())
// {
// var defaultShardingDbContext = scope.ServiceProvider.GetService<OtherDbContext>();
// var defaultShardingDbContext = scope.ServiceProvider.GetService<DefaultShardingDbContext>();
// // if (defaultShardingDbContext.Database.GetPendingMigrations().Any())
// {
// try
Expand All @@ -209,6 +209,10 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
// {
// }
// }
// // var shardingRuntimeContext = defaultShardingDbContext.GetShardingRuntimeContext();
// // var tableRouteManager = shardingRuntimeContext.GetTableRouteManager();
// // var virtualTableRoute = (SysUserLogByMonthRoute)tableRouteManager.GetRoute(typeof(SysUserLogByMonth));
// // virtualTableRoute.Append("2021");
// }
//
// app.ApplicationServices.UseAutoTryCompensateTable(12);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ public void AddExtraDataSource(Func<IShardingProvider, IDictionary<string, strin
/// <param name="defaultPriority">默认优先级建议大于0</param>
/// <param name="readConnStringGetStrategy">LatestFirstTime:DbContext缓存,LatestEveryTime:每次都是最新</param>
/// <exception cref="ArgumentNullException"></exception>
[Obsolete("plz use AddReadWriteSeparation param use ReadWriteDefaultEnableBehavior")]
public void AddReadWriteSeparation(
Func<IShardingProvider, IDictionary<string, IEnumerable<string>>> readWriteSeparationConfigure,
ReadStrategyEnum readStrategyEnum,
Expand All @@ -125,7 +126,31 @@ public void AddReadWriteSeparation(
ShardingReadWriteSeparationOptions = new ShardingReadWriteSeparationOptions();
ShardingReadWriteSeparationOptions.ReadWriteSeparationConfigure= readWriteSeparationConfigure ?? throw new ArgumentNullException(nameof(readWriteSeparationConfigure));
ShardingReadWriteSeparationOptions.ReadStrategy = readStrategyEnum;
ShardingReadWriteSeparationOptions.DefaultEnable=defaultEnable;
ShardingReadWriteSeparationOptions.DefaultEnableBehavior=defaultEnable?ReadWriteDefaultEnableBehavior.DefaultEnable:ReadWriteDefaultEnableBehavior.DefaultDisable;
ShardingReadWriteSeparationOptions.DefaultPriority= defaultPriority;
ShardingReadWriteSeparationOptions.ReadConnStringGetStrategy= readConnStringGetStrategy;
}
/// <summary>
/// 添加读写分离配置
/// </summary>
/// <param name="readWriteSeparationConfigure"></param>
/// <param name="readStrategyEnum">随机或者轮询</param>
/// <param name="defaultEnableBehavior"></param>
/// <param name="defaultEnable">DefaultDisable表示哪怕您添加了读写分离也不会进行读写分离查询,只有需要的时候自行开启,DefaultEnable表示默认查询就是走的读写分离,InTransactionEnable在事务中的查询使用读写分离,InTransactionDisbale在事务中不使用读写分离</param>
/// <param name="defaultPriority">默认优先级建议大于0</param>
/// <param name="readConnStringGetStrategy">LatestFirstTime:DbContext缓存,LatestEveryTime:每次都是最新</param>
/// <exception cref="ArgumentNullException"></exception>
public void AddReadWriteSeparation(
Func<IShardingProvider, IDictionary<string, IEnumerable<string>>> readWriteSeparationConfigure,
ReadStrategyEnum readStrategyEnum,
ReadWriteDefaultEnableBehavior defaultEnableBehavior = ReadWriteDefaultEnableBehavior.DefaultDisable,
int defaultPriority = 10,
ReadConnStringGetStrategyEnum readConnStringGetStrategy = ReadConnStringGetStrategyEnum.LatestFirstTime)
{
ShardingReadWriteSeparationOptions = new ShardingReadWriteSeparationOptions();
ShardingReadWriteSeparationOptions.ReadWriteSeparationConfigure= readWriteSeparationConfigure ?? throw new ArgumentNullException(nameof(readWriteSeparationConfigure));
ShardingReadWriteSeparationOptions.ReadStrategy = readStrategyEnum;
ShardingReadWriteSeparationOptions.DefaultEnableBehavior=defaultEnableBehavior;
ShardingReadWriteSeparationOptions.DefaultPriority= defaultPriority;
ShardingReadWriteSeparationOptions.ReadConnStringGetStrategy= readConnStringGetStrategy;
}
Expand All @@ -148,6 +173,7 @@ public void AddReadWriteSeparation(
/// <param name="defaultPriority"></param>
/// <param name="readConnStringGetStrategy"></param>
/// <exception cref="ArgumentNullException"></exception>
[Obsolete("plz use AddReadWriteNodeSeparation param use ReadWriteDefaultEnableBehavior")]
public void AddReadWriteNodeSeparation(
Func<IShardingProvider, IDictionary<string, IEnumerable<ReadNode>>> readWriteNodeSeparationConfigure,
ReadStrategyEnum readStrategyEnum,
Expand All @@ -158,7 +184,40 @@ public void AddReadWriteNodeSeparation(
ShardingReadWriteSeparationOptions = new ShardingReadWriteSeparationOptions();
ShardingReadWriteSeparationOptions.ReadWriteNodeSeparationConfigure= readWriteNodeSeparationConfigure ?? throw new ArgumentNullException(nameof(readWriteNodeSeparationConfigure));
ShardingReadWriteSeparationOptions.ReadStrategy = readStrategyEnum;
ShardingReadWriteSeparationOptions.DefaultEnable=defaultEnable;
ShardingReadWriteSeparationOptions.DefaultEnableBehavior=defaultEnable?ReadWriteDefaultEnableBehavior.DefaultEnable:ReadWriteDefaultEnableBehavior.DefaultDisable;
ShardingReadWriteSeparationOptions.DefaultPriority= defaultPriority;
ShardingReadWriteSeparationOptions.ReadConnStringGetStrategy= readConnStringGetStrategy;
}
/// <summary>
/// 读写分离配置 和 AddReadWriteSeparation不同的是
/// 当前配置支持自定义读链接节点命名,命名的好处在于当使用读库链接的时候由于服务器性能的差异
/// 可以将部分吃性能的查询通过节点名称切换到对应的性能相对较好或者较空闲的读库服务器
/// <code><![CDATA[
/// IShardingReadWriteManager _readWriteManager=...
/// using (_readWriteManager.CreateScope())
/// {
/// _readWriteManager.GetCurrent().SetReadWriteSeparation(100,true);
/// _readWriteManager.GetCurrent().AddDataSourceReadNode("A", readNodeName);
/// var xxxaaa = await _defaultTableDbContext.Set<SysUserSalary>().FirstOrDefaultAsync();
/// }]]></code>
/// </summary>
/// <param name="readWriteNodeSeparationConfigure"></param>
/// <param name="readStrategyEnum"></param>
/// <param name="defaultEnableBehavior"></param>
/// <param name="defaultPriority"></param>
/// <param name="readConnStringGetStrategy"></param>
/// <exception cref="ArgumentNullException"></exception>
public void AddReadWriteNodeSeparation(
Func<IShardingProvider, IDictionary<string, IEnumerable<ReadNode>>> readWriteNodeSeparationConfigure,
ReadStrategyEnum readStrategyEnum,
ReadWriteDefaultEnableBehavior defaultEnableBehavior = ReadWriteDefaultEnableBehavior.DefaultDisable,
int defaultPriority = 10,
ReadConnStringGetStrategyEnum readConnStringGetStrategy = ReadConnStringGetStrategyEnum.LatestFirstTime)
{
ShardingReadWriteSeparationOptions = new ShardingReadWriteSeparationOptions();
ShardingReadWriteSeparationOptions.ReadWriteNodeSeparationConfigure= readWriteNodeSeparationConfigure ?? throw new ArgumentNullException(nameof(readWriteNodeSeparationConfigure));
ShardingReadWriteSeparationOptions.ReadStrategy = readStrategyEnum;
ShardingReadWriteSeparationOptions.DefaultEnableBehavior=defaultEnableBehavior;
ShardingReadWriteSeparationOptions.DefaultPriority= defaultPriority;
ShardingReadWriteSeparationOptions.ReadConnStringGetStrategy= readConnStringGetStrategy;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,26 @@ namespace ShardingCore.Core.ShardingConfigurations
{
public class ShardingReadWriteSeparationOptions
{
public Func<IShardingProvider, IDictionary<string, IEnumerable<string>>> ReadWriteSeparationConfigure { get; set; }
public Func<IShardingProvider, IDictionary<string, IEnumerable<ReadNode>>> ReadWriteNodeSeparationConfigure { get; set; }
public Func<IShardingProvider, IDictionary<string, IEnumerable<string>>> ReadWriteSeparationConfigure
{
get;
set;
}

public Func<IShardingProvider, IDictionary<string, IEnumerable<ReadNode>>> ReadWriteNodeSeparationConfigure
{
get;
set;
}

public ReadStrategyEnum ReadStrategy { get; set; } = ReadStrategyEnum.Loop;
public bool DefaultEnable { get; set; } = false;
// public bool DefaultEnable { get; set; } = false;
public int DefaultPriority { get; set; } = 10;

public ReadWriteDefaultEnableBehavior DefaultEnableBehavior { get; set; } =
ReadWriteDefaultEnableBehavior.DefaultDisable;

public ReadConnStringGetStrategyEnum ReadConnStringGetStrategy { get; set; } =
ReadConnStringGetStrategyEnum.LatestFirstTime;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public abstract class AbstractVirtualDataSourceConfigurationParams:IVirtualDataS
public virtual IDictionary<string, string> ExtraDataSources { get; }=new ConcurrentDictionary<string, string>();
public virtual IDictionary<string, ReadNode[]> ReadWriteNodeSeparationConfigs { get; }
public virtual ReadStrategyEnum? ReadStrategy { get; }
public virtual bool? ReadWriteDefaultEnable { get; }
public virtual ReadWriteDefaultEnableBehavior? ReadWriteDefaultEnableBehavior { get; }
public virtual int? ReadWriteDefaultPriority { get; }
public virtual ReadConnStringGetStrategyEnum? ReadConnStringGetStrategy { get; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public interface IVirtualDataSourceConfigurationParams
IDictionary<string, ReadNode[]> ReadWriteNodeSeparationConfigs { get; }

ReadStrategyEnum? ReadStrategy { get; }
bool? ReadWriteDefaultEnable { get; }
ReadWriteDefaultEnableBehavior? ReadWriteDefaultEnableBehavior { get; }
int? ReadWriteDefaultPriority { get; }
/// <summary>
/// 读写分离链接字符串获取
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public class SimpleVirtualDataSourceConfigurationParams: AbstractVirtualDataSour
public override IDictionary<string, string> ExtraDataSources { get; }
public override IDictionary<string, ReadNode[]> ReadWriteNodeSeparationConfigs { get; }
public override ReadStrategyEnum? ReadStrategy { get; }
public override bool? ReadWriteDefaultEnable { get; }
public override ReadWriteDefaultEnableBehavior? ReadWriteDefaultEnableBehavior { get; }
public override int? ReadWriteDefaultPriority { get; }
public override ReadConnStringGetStrategyEnum? ReadConnStringGetStrategy { get; }

Expand Down Expand Up @@ -57,7 +57,7 @@ public SimpleVirtualDataSourceConfigurationParams(IShardingProvider shardingProv
}
}
ReadStrategy = options.ShardingReadWriteSeparationOptions.ReadStrategy;
ReadWriteDefaultEnable = options.ShardingReadWriteSeparationOptions.DefaultEnable;
ReadWriteDefaultEnableBehavior = options.ShardingReadWriteSeparationOptions.DefaultEnableBehavior;
ReadWriteDefaultPriority = options.ShardingReadWriteSeparationOptions.DefaultPriority;
ReadConnStringGetStrategy = options.ShardingReadWriteSeparationOptions.ReadConnStringGetStrategy;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,9 @@ private void CheckReadWriteSeparation()
{
throw new ArgumentException(nameof(ConfigurationParams.ReadConnStringGetStrategy));
}
if (!ConfigurationParams.ReadWriteDefaultEnable.HasValue)
if (!ConfigurationParams.ReadWriteDefaultEnableBehavior.HasValue)
{
throw new ArgumentException(nameof(ConfigurationParams.ReadWriteDefaultEnable));
throw new ArgumentException(nameof(ConfigurationParams.ReadWriteDefaultEnableBehavior));
}
if (!ConfigurationParams.ReadWriteDefaultPriority.HasValue)
{
Expand Down
28 changes: 27 additions & 1 deletion src/ShardingCore/Extensions/ShardingReadWriteExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ private static void SetReadWriteSeparation(this IShardingDbContext shardingDbCon
}
}

shardingDbContextExecutor.ReadWriteSeparation = readOnly;
shardingDbContextExecutor.ReadWriteSeparationBehavior = ReadWriteDefaultEnableBehavior.DefaultEnable;
}

public static void SetReadWriteSeparation(this ShardingReadWriteContext shardingReadWriteContext, int priority,
Expand All @@ -76,6 +76,7 @@ public static void SetReadWriteSeparation(this ShardingReadWriteContext sharding
/// </summary>
/// <param name="shardingDbContext"></param>
/// <returns></returns>
[Obsolete(" plz use CurrentIsReadWriteSeparationBehavior")]
public static bool CurrentIsReadWriteSeparation(this IShardingDbContext shardingDbContext)
{
if (shardingDbContext.IsUseReadWriteSeparation())
Expand All @@ -101,5 +102,30 @@ public static bool CurrentIsReadWriteSeparation(this IShardingDbContext sharding

return false;
}
public static ReadWriteDefaultEnableBehavior CurrentIsReadWriteSeparationBehavior(this IShardingDbContext shardingDbContext)
{
if (shardingDbContext.IsUseReadWriteSeparation())
{
var shardingRuntimeContext = ((DbContext)shardingDbContext).GetShardingRuntimeContext();
var shardingDbContextExecutor = shardingDbContext.GetShardingExecutor();
var shardingReadWriteManager = shardingRuntimeContext.GetService<IShardingReadWriteManager>();
var shardingReadWriteContext = shardingReadWriteManager.GetCurrent();
if (shardingReadWriteContext != null)
{
if (shardingReadWriteContext.DefaultPriority > shardingDbContextExecutor.ReadWriteSeparationPriority)
{
return shardingReadWriteContext.DefaultEnableBehavior;
}
else
{
return shardingDbContextExecutor.ReadWriteSeparationBehavior;
}
}

return shardingDbContextExecutor.ReadWriteSeparationBehavior;
}

return ReadWriteDefaultEnableBehavior.DefaultDisable;
}
}
}
1 change: 1 addition & 0 deletions src/ShardingCore/Sharding/Abstractions/IReadWriteSwitch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,6 @@ public interface IReadWriteSwitch
{
int ReadWriteSeparationPriority { get; set; }
bool ReadWriteSeparation { get; set; }
ReadWriteDefaultEnableBehavior ReadWriteSeparationBehavior { get; set; }
}
}
Loading

0 comments on commit 13c76f4

Please sign in to comment.