读写分离添加默认行为方式

This commit is contained in:
xuejiaming 2023-05-11 12:25:46 +08:00
parent 9ae39a5a5c
commit 13c76f4be3
24 changed files with 229 additions and 34 deletions

View File

@ -318,5 +318,41 @@ namespace Sample.MySql.Controllers
// var sysUserMods2 = await _defaultTableDbContext.Set<SysTest>().FromSqlRaw("select * from SysTest where id='2'").ToListAsync(); // var sysUserMods2 = await _defaultTableDbContext.Set<SysTest>().FromSqlRaw("select * from SysTest where id='2'").ToListAsync();
return Ok(); 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();
}
} }
} }

View File

@ -197,7 +197,7 @@ namespace Sample.MySql
// app.ApplicationServices.UseAutoTryCompensateTable(); // app.ApplicationServices.UseAutoTryCompensateTable();
// using (var scope = app.ApplicationServices.CreateScope()) // using (var scope = app.ApplicationServices.CreateScope())
// { // {
// var defaultShardingDbContext = scope.ServiceProvider.GetService<OtherDbContext>(); // var defaultShardingDbContext = scope.ServiceProvider.GetService<DefaultShardingDbContext>();
// // if (defaultShardingDbContext.Database.GetPendingMigrations().Any()) // // if (defaultShardingDbContext.Database.GetPendingMigrations().Any())
// { // {
// try // try
@ -209,6 +209,10 @@ namespace Sample.MySql
// { // {
// } // }
// } // }
// // var shardingRuntimeContext = defaultShardingDbContext.GetShardingRuntimeContext();
// // var tableRouteManager = shardingRuntimeContext.GetTableRouteManager();
// // var virtualTableRoute = (SysUserLogByMonthRoute)tableRouteManager.GetRoute(typeof(SysUserLogByMonth));
// // virtualTableRoute.Append("2021");
// } // }
// //
// app.ApplicationServices.UseAutoTryCompensateTable(12); // app.ApplicationServices.UseAutoTryCompensateTable(12);

View File

@ -115,6 +115,7 @@ namespace ShardingCore.Core.ShardingConfigurations
/// <param name="defaultPriority">默认优先级建议大于0</param> /// <param name="defaultPriority">默认优先级建议大于0</param>
/// <param name="readConnStringGetStrategy">LatestFirstTime:DbContext缓存,LatestEveryTime:每次都是最新</param> /// <param name="readConnStringGetStrategy">LatestFirstTime:DbContext缓存,LatestEveryTime:每次都是最新</param>
/// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentNullException"></exception>
[Obsolete("plz use AddReadWriteSeparation param use ReadWriteDefaultEnableBehavior")]
public void AddReadWriteSeparation( public void AddReadWriteSeparation(
Func<IShardingProvider, IDictionary<string, IEnumerable<string>>> readWriteSeparationConfigure, Func<IShardingProvider, IDictionary<string, IEnumerable<string>>> readWriteSeparationConfigure,
ReadStrategyEnum readStrategyEnum, ReadStrategyEnum readStrategyEnum,
@ -125,7 +126,31 @@ namespace ShardingCore.Core.ShardingConfigurations
ShardingReadWriteSeparationOptions = new ShardingReadWriteSeparationOptions(); ShardingReadWriteSeparationOptions = new ShardingReadWriteSeparationOptions();
ShardingReadWriteSeparationOptions.ReadWriteSeparationConfigure= readWriteSeparationConfigure ?? throw new ArgumentNullException(nameof(readWriteSeparationConfigure)); ShardingReadWriteSeparationOptions.ReadWriteSeparationConfigure= readWriteSeparationConfigure ?? throw new ArgumentNullException(nameof(readWriteSeparationConfigure));
ShardingReadWriteSeparationOptions.ReadStrategy = readStrategyEnum; 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.DefaultPriority= defaultPriority;
ShardingReadWriteSeparationOptions.ReadConnStringGetStrategy= readConnStringGetStrategy; ShardingReadWriteSeparationOptions.ReadConnStringGetStrategy= readConnStringGetStrategy;
} }
@ -148,6 +173,7 @@ namespace ShardingCore.Core.ShardingConfigurations
/// <param name="defaultPriority"></param> /// <param name="defaultPriority"></param>
/// <param name="readConnStringGetStrategy"></param> /// <param name="readConnStringGetStrategy"></param>
/// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentNullException"></exception>
[Obsolete("plz use AddReadWriteNodeSeparation param use ReadWriteDefaultEnableBehavior")]
public void AddReadWriteNodeSeparation( public void AddReadWriteNodeSeparation(
Func<IShardingProvider, IDictionary<string, IEnumerable<ReadNode>>> readWriteNodeSeparationConfigure, Func<IShardingProvider, IDictionary<string, IEnumerable<ReadNode>>> readWriteNodeSeparationConfigure,
ReadStrategyEnum readStrategyEnum, ReadStrategyEnum readStrategyEnum,
@ -158,7 +184,40 @@ namespace ShardingCore.Core.ShardingConfigurations
ShardingReadWriteSeparationOptions = new ShardingReadWriteSeparationOptions(); ShardingReadWriteSeparationOptions = new ShardingReadWriteSeparationOptions();
ShardingReadWriteSeparationOptions.ReadWriteNodeSeparationConfigure= readWriteNodeSeparationConfigure ?? throw new ArgumentNullException(nameof(readWriteNodeSeparationConfigure)); ShardingReadWriteSeparationOptions.ReadWriteNodeSeparationConfigure= readWriteNodeSeparationConfigure ?? throw new ArgumentNullException(nameof(readWriteNodeSeparationConfigure));
ShardingReadWriteSeparationOptions.ReadStrategy = readStrategyEnum; 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.DefaultPriority= defaultPriority;
ShardingReadWriteSeparationOptions.ReadConnStringGetStrategy= readConnStringGetStrategy; ShardingReadWriteSeparationOptions.ReadConnStringGetStrategy= readConnStringGetStrategy;
} }

View File

@ -7,14 +7,26 @@ namespace ShardingCore.Core.ShardingConfigurations
{ {
public class ShardingReadWriteSeparationOptions public class ShardingReadWriteSeparationOptions
{ {
public Func<IShardingProvider, IDictionary<string, IEnumerable<string>>> ReadWriteSeparationConfigure { get; set; } public Func<IShardingProvider, IDictionary<string, IEnumerable<string>>> ReadWriteSeparationConfigure
public Func<IShardingProvider, IDictionary<string, IEnumerable<ReadNode>>> ReadWriteNodeSeparationConfigure { get; set; } {
get;
set;
}
public Func<IShardingProvider, IDictionary<string, IEnumerable<ReadNode>>> ReadWriteNodeSeparationConfigure
{
get;
set;
}
public ReadStrategyEnum ReadStrategy { get; set; } = ReadStrategyEnum.Loop; 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 int DefaultPriority { get; set; } = 10;
public ReadWriteDefaultEnableBehavior DefaultEnableBehavior { get; set; } =
ReadWriteDefaultEnableBehavior.DefaultDisable;
public ReadConnStringGetStrategyEnum ReadConnStringGetStrategy { get; set; } = public ReadConnStringGetStrategyEnum ReadConnStringGetStrategy { get; set; } =
ReadConnStringGetStrategyEnum.LatestFirstTime; ReadConnStringGetStrategyEnum.LatestFirstTime;
} }
} }

View File

@ -21,7 +21,7 @@ namespace ShardingCore.Core.VirtualDatabase.VirtualDataSources.Abstractions
public virtual IDictionary<string, string> ExtraDataSources { get; }=new ConcurrentDictionary<string, string>(); public virtual IDictionary<string, string> ExtraDataSources { get; }=new ConcurrentDictionary<string, string>();
public virtual IDictionary<string, ReadNode[]> ReadWriteNodeSeparationConfigs { get; } public virtual IDictionary<string, ReadNode[]> ReadWriteNodeSeparationConfigs { get; }
public virtual ReadStrategyEnum? ReadStrategy { get; } public virtual ReadStrategyEnum? ReadStrategy { get; }
public virtual bool? ReadWriteDefaultEnable { get; } public virtual ReadWriteDefaultEnableBehavior? ReadWriteDefaultEnableBehavior { get; }
public virtual int? ReadWriteDefaultPriority { get; } public virtual int? ReadWriteDefaultPriority { get; }
public virtual ReadConnStringGetStrategyEnum? ReadConnStringGetStrategy { get; } public virtual ReadConnStringGetStrategyEnum? ReadConnStringGetStrategy { get; }

View File

@ -36,7 +36,7 @@ namespace ShardingCore.Core.VirtualDatabase.VirtualDataSources.Abstractions
IDictionary<string, ReadNode[]> ReadWriteNodeSeparationConfigs { get; } IDictionary<string, ReadNode[]> ReadWriteNodeSeparationConfigs { get; }
ReadStrategyEnum? ReadStrategy { get; } ReadStrategyEnum? ReadStrategy { get; }
bool? ReadWriteDefaultEnable { get; } ReadWriteDefaultEnableBehavior? ReadWriteDefaultEnableBehavior { get; }
int? ReadWriteDefaultPriority { get; } int? ReadWriteDefaultPriority { get; }
/// <summary> /// <summary>
/// 读写分离链接字符串获取 /// 读写分离链接字符串获取

View File

@ -23,7 +23,7 @@ namespace ShardingCore.Core.VirtualDatabase.VirtualDataSources
public override IDictionary<string, string> ExtraDataSources { get; } public override IDictionary<string, string> ExtraDataSources { get; }
public override IDictionary<string, ReadNode[]> ReadWriteNodeSeparationConfigs { get; } public override IDictionary<string, ReadNode[]> ReadWriteNodeSeparationConfigs { get; }
public override ReadStrategyEnum? ReadStrategy { get; } public override ReadStrategyEnum? ReadStrategy { get; }
public override bool? ReadWriteDefaultEnable { get; } public override ReadWriteDefaultEnableBehavior? ReadWriteDefaultEnableBehavior { get; }
public override int? ReadWriteDefaultPriority { get; } public override int? ReadWriteDefaultPriority { get; }
public override ReadConnStringGetStrategyEnum? ReadConnStringGetStrategy { get; } public override ReadConnStringGetStrategyEnum? ReadConnStringGetStrategy { get; }
@ -57,7 +57,7 @@ namespace ShardingCore.Core.VirtualDatabase.VirtualDataSources
} }
} }
ReadStrategy = options.ShardingReadWriteSeparationOptions.ReadStrategy; ReadStrategy = options.ShardingReadWriteSeparationOptions.ReadStrategy;
ReadWriteDefaultEnable = options.ShardingReadWriteSeparationOptions.DefaultEnable; ReadWriteDefaultEnableBehavior = options.ShardingReadWriteSeparationOptions.DefaultEnableBehavior;
ReadWriteDefaultPriority = options.ShardingReadWriteSeparationOptions.DefaultPriority; ReadWriteDefaultPriority = options.ShardingReadWriteSeparationOptions.DefaultPriority;
ReadConnStringGetStrategy = options.ShardingReadWriteSeparationOptions.ReadConnStringGetStrategy; ReadConnStringGetStrategy = options.ShardingReadWriteSeparationOptions.ReadConnStringGetStrategy;
} }

View File

@ -77,9 +77,9 @@ namespace ShardingCore.Core.VirtualDatabase.VirtualDataSources
{ {
throw new ArgumentException(nameof(ConfigurationParams.ReadConnStringGetStrategy)); 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) if (!ConfigurationParams.ReadWriteDefaultPriority.HasValue)
{ {

View File

@ -61,7 +61,7 @@ namespace ShardingCore.Extensions
} }
} }
shardingDbContextExecutor.ReadWriteSeparation = readOnly; shardingDbContextExecutor.ReadWriteSeparationBehavior = ReadWriteDefaultEnableBehavior.DefaultEnable;
} }
public static void SetReadWriteSeparation(this ShardingReadWriteContext shardingReadWriteContext, int priority, public static void SetReadWriteSeparation(this ShardingReadWriteContext shardingReadWriteContext, int priority,
@ -76,6 +76,7 @@ namespace ShardingCore.Extensions
/// </summary> /// </summary>
/// <param name="shardingDbContext"></param> /// <param name="shardingDbContext"></param>
/// <returns></returns> /// <returns></returns>
[Obsolete(" plz use CurrentIsReadWriteSeparationBehavior")]
public static bool CurrentIsReadWriteSeparation(this IShardingDbContext shardingDbContext) public static bool CurrentIsReadWriteSeparation(this IShardingDbContext shardingDbContext)
{ {
if (shardingDbContext.IsUseReadWriteSeparation()) if (shardingDbContext.IsUseReadWriteSeparation())
@ -101,5 +102,30 @@ namespace ShardingCore.Extensions
return false; 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;
}
} }
} }

View File

@ -17,5 +17,6 @@ namespace ShardingCore.Sharding.Abstractions
{ {
int ReadWriteSeparationPriority { get; set; } int ReadWriteSeparationPriority { get; set; }
bool ReadWriteSeparation { get; set; } bool ReadWriteSeparation { get; set; }
ReadWriteDefaultEnableBehavior ReadWriteSeparationBehavior { get; set; }
} }
} }

View File

@ -19,23 +19,25 @@ namespace ShardingCore.Sharding
*/ */
public class ActualConnectionStringManager public class ActualConnectionStringManager
{ {
public DbContext ShellDbContext { get; }
private readonly bool _useReadWriteSeparation; private readonly bool _useReadWriteSeparation;
private readonly IShardingReadWriteManager _shardingReadWriteManager; private readonly IShardingReadWriteManager _shardingReadWriteManager;
private readonly IVirtualDataSource _virtualDataSource; private readonly IVirtualDataSource _virtualDataSource;
public int ReadWriteSeparationPriority { get; set; } public int ReadWriteSeparationPriority { get; set; }
public bool ReadWriteSeparation { get; set; } public ReadWriteDefaultEnableBehavior ReadWriteSeparation { get; set; }
public ReadStrategyEnum ReadStrategy { get; set; } public ReadStrategyEnum ReadStrategy { get; set; }
public ReadConnStringGetStrategyEnum ReadConnStringGetStrategy { get; set; } public ReadConnStringGetStrategyEnum ReadConnStringGetStrategy { get; set; }
private string _cacheConnectionString; private string _cacheConnectionString;
public ActualConnectionStringManager(IShardingReadWriteManager shardingReadWriteManager,IVirtualDataSource virtualDataSource) public ActualConnectionStringManager(IShardingReadWriteManager shardingReadWriteManager,IVirtualDataSource virtualDataSource,DbContext shellDbContext)
{ {
ShellDbContext = shellDbContext;
_shardingReadWriteManager = shardingReadWriteManager; _shardingReadWriteManager = shardingReadWriteManager;
_virtualDataSource=virtualDataSource; _virtualDataSource=virtualDataSource;
_useReadWriteSeparation = virtualDataSource.ConnectionStringManager is ReadWriteConnectionStringManager; _useReadWriteSeparation = virtualDataSource.ConnectionStringManager is ReadWriteConnectionStringManager;
if (_useReadWriteSeparation) if (_useReadWriteSeparation)
{ {
ReadWriteSeparationPriority = virtualDataSource.ConfigurationParams.ReadWriteDefaultPriority.GetValueOrDefault(); ReadWriteSeparationPriority = virtualDataSource.ConfigurationParams.ReadWriteDefaultPriority.GetValueOrDefault();
ReadWriteSeparation = virtualDataSource.ConfigurationParams.ReadWriteDefaultEnable.GetValueOrDefault(); ReadWriteSeparation = virtualDataSource.ConfigurationParams.ReadWriteDefaultEnableBehavior.GetValueOrDefault(ReadWriteDefaultEnableBehavior.DefaultDisable);
ReadStrategy = virtualDataSource.ConfigurationParams.ReadStrategy.GetValueOrDefault(); ReadStrategy = virtualDataSource.ConfigurationParams.ReadStrategy.GetValueOrDefault();
ReadConnStringGetStrategy = virtualDataSource.ConfigurationParams.ReadConnStringGetStrategy.GetValueOrDefault(); ReadConnStringGetStrategy = virtualDataSource.ConfigurationParams.ReadConnStringGetStrategy.GetValueOrDefault();
} }
@ -62,9 +64,25 @@ namespace ShardingCore.Sharding
return _virtualDataSource.GetConnectionString(dataSourceName); return _virtualDataSource.GetConnectionString(dataSourceName);
} }
private bool useReadWriteSeparation(ReadWriteDefaultEnableBehavior behavior,bool inTransaction)
{
if (behavior == ReadWriteDefaultEnableBehavior.DefaultEnable)
{
return true;
}
if (behavior == ReadWriteDefaultEnableBehavior.OutTransactionEnable)
{
return !inTransaction;
}
return false;
}
private string GetReadWriteSeparationConnectString(string dataSourceName) private string GetReadWriteSeparationConnectString(string dataSourceName)
{ {
var support = ReadWriteSeparation; bool inTransaction=ShellDbContext.Database.CurrentTransaction != null;
var support = useReadWriteSeparation(ReadWriteSeparation,inTransaction);
string readNodeName = null; string readNodeName = null;
var hasConfig = false; var hasConfig = false;
var shardingReadWriteContext = _shardingReadWriteManager.GetCurrent(); var shardingReadWriteContext = _shardingReadWriteManager.GetCurrent();
@ -72,8 +90,8 @@ namespace ShardingCore.Sharding
{ {
var dbFirst = ReadWriteSeparationPriority >= shardingReadWriteContext.DefaultPriority; var dbFirst = ReadWriteSeparationPriority >= shardingReadWriteContext.DefaultPriority;
support = dbFirst support = dbFirst
? ReadWriteSeparation ? useReadWriteSeparation(ReadWriteSeparation,inTransaction)
: shardingReadWriteContext.DefaultReadEnable; : useReadWriteSeparation(shardingReadWriteContext.DefaultEnableBehavior,inTransaction);
if (!dbFirst&& support) if (!dbFirst&& support)
{ {
hasConfig = shardingReadWriteContext.TryGetDataSourceReadNode(dataSourceName, out readNodeName); hasConfig = shardingReadWriteContext.TryGetDataSourceReadNode(dataSourceName, out readNodeName);

View File

@ -0,0 +1,15 @@
namespace ShardingCore.Sharding.ReadWriteConfigurations
{
/**
*
*/
public enum ReadWriteDefaultEnableBehavior
{
//默认不启用
DefaultDisable,
//默认启用
DefaultEnable,
//不在事务中启用
OutTransactionEnable
}
}

View File

@ -13,13 +13,27 @@ namespace ShardingCore.Sharding.ReadWriteConfigurations
*/ */
public class ShardingReadWriteContext public class ShardingReadWriteContext
{ {
public bool DefaultReadEnable { get; set; } [Obsolete("use DefaultEnableBehavior")]
public bool DefaultReadEnable
{
get { return DefaultEnableBehavior == ReadWriteDefaultEnableBehavior.DefaultEnable; }
set
{
DefaultEnableBehavior =
value
? ReadWriteDefaultEnableBehavior.DefaultEnable
: ReadWriteDefaultEnableBehavior.DefaultDisable;
}
}
public ReadWriteDefaultEnableBehavior DefaultEnableBehavior { get; set; }
public int DefaultPriority { get; set; } public int DefaultPriority { get; set; }
private readonly Dictionary<string /*数据源*/, string /*数据源对应的读节点名称*/> _dataSourceReadNode; private readonly Dictionary<string /*数据源*/, string /*数据源对应的读节点名称*/> _dataSourceReadNode;
private ShardingReadWriteContext() private ShardingReadWriteContext()
{ {
DefaultReadEnable = false; DefaultReadEnable = false;
DefaultEnableBehavior = ReadWriteDefaultEnableBehavior.DefaultDisable;
DefaultPriority = 0; DefaultPriority = 0;
_dataSourceReadNode = new Dictionary<string, string>(); _dataSourceReadNode = new Dictionary<string, string>();
} }
@ -28,6 +42,7 @@ namespace ShardingCore.Sharding.ReadWriteConfigurations
{ {
return new ShardingReadWriteContext(); return new ShardingReadWriteContext();
} }
/// <summary> /// <summary>
/// 添加数据源对应读节点获取名称 /// 添加数据源对应读节点获取名称
/// </summary> /// </summary>
@ -40,18 +55,20 @@ namespace ShardingCore.Sharding.ReadWriteConfigurations
{ {
return false; return false;
} }
_dataSourceReadNode.Add(dataSource, readNodeName); _dataSourceReadNode.Add(dataSource, readNodeName);
return true; return true;
} }
/// <summary> /// <summary>
/// 尝试获取对应数据源的读节点名称 /// 尝试获取对应数据源的读节点名称
/// </summary> /// </summary>
/// <param name="dataSource"></param> /// <param name="dataSource"></param>
/// <param name="readNodeName"></param> /// <param name="readNodeName"></param>
/// <returns></returns> /// <returns></returns>
public bool TryGetDataSourceReadNode(string dataSource,out string readNodeName) public bool TryGetDataSourceReadNode(string dataSource, out string readNodeName)
{ {
return _dataSourceReadNode.TryGetValue(dataSource, out readNodeName); return _dataSourceReadNode.TryGetValue(dataSource, out readNodeName);
} }
} }
} }

View File

@ -66,7 +66,14 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors
set => _actualConnectionStringManager.ReadWriteSeparationPriority = value; set => _actualConnectionStringManager.ReadWriteSeparationPriority = value;
} }
[Obsolete("use ReadWriteSeparationBehavior")]
public bool ReadWriteSeparation public bool ReadWriteSeparation
{
get => _actualConnectionStringManager.ReadWriteSeparation==ReadWriteDefaultEnableBehavior.DefaultEnable;
set => _actualConnectionStringManager.ReadWriteSeparation = value?ReadWriteDefaultEnableBehavior.DefaultEnable:ReadWriteDefaultEnableBehavior.DefaultDisable;
}
public ReadWriteDefaultEnableBehavior ReadWriteSeparationBehavior
{ {
get => _actualConnectionStringManager.ReadWriteSeparation; get => _actualConnectionStringManager.ReadWriteSeparation;
set => _actualConnectionStringManager.ReadWriteSeparation = value; set => _actualConnectionStringManager.ReadWriteSeparation = value;
@ -92,7 +99,7 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors
var loggerFactory = shardingProvider.GetRequiredService<ILoggerFactory>(); var loggerFactory = shardingProvider.GetRequiredService<ILoggerFactory>();
_logger = loggerFactory.CreateLogger<ShardingDbContextExecutor>(); _logger = loggerFactory.CreateLogger<ShardingDbContextExecutor>();
_actualConnectionStringManager = _actualConnectionStringManager =
new ActualConnectionStringManager(shardingReadWriteManager, _virtualDataSource); new ActualConnectionStringManager(shardingReadWriteManager, _virtualDataSource,_shardingDbContext);
} }
#region create db context #region create db context

View File

@ -58,7 +58,7 @@ namespace ShardingCore.Test
_shardingRouteManager = shardingRuntimeContext.GetShardingRouteManager(); _shardingRouteManager = shardingRuntimeContext.GetShardingRouteManager();
_shardingReadWriteManager = shardingRuntimeContext.GetShardingReadWriteManager(); _shardingReadWriteManager = shardingRuntimeContext.GetShardingReadWriteManager();
_virtualDataSource = shardingRuntimeContext.GetVirtualDataSource(); _virtualDataSource = shardingRuntimeContext.GetVirtualDataSource();
_connectionStringManager = new ActualConnectionStringManager(_shardingReadWriteManager, _virtualDataSource); _connectionStringManager = new ActualConnectionStringManager(_shardingReadWriteManager, _virtualDataSource,virtualDbContext);
_configuration = configuration; _configuration = configuration;
_entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager(); _entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager();
_tableRouteManager = shardingRuntimeContext.GetTableRouteManager(); _tableRouteManager = shardingRuntimeContext.GetTableRouteManager();

View File

@ -52,7 +52,7 @@ namespace ShardingCore.Test
_shardingRouteManager = shardingRuntimeContext.GetShardingRouteManager(); _shardingRouteManager = shardingRuntimeContext.GetShardingRouteManager();
_shardingReadWriteManager = shardingRuntimeContext.GetShardingReadWriteManager(); _shardingReadWriteManager = shardingRuntimeContext.GetShardingReadWriteManager();
_virtualDataSource = shardingRuntimeContext.GetVirtualDataSource(); _virtualDataSource = shardingRuntimeContext.GetVirtualDataSource();
_connectionStringManager = new ActualConnectionStringManager(_shardingReadWriteManager,_virtualDataSource); _connectionStringManager = new ActualConnectionStringManager(_shardingReadWriteManager,_virtualDataSource,virtualDbContext);
_configuration = configuration; _configuration = configuration;
_entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager(); _entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager();
_tableRouteManager = shardingRuntimeContext.GetTableRouteManager(); _tableRouteManager = shardingRuntimeContext.GetTableRouteManager();

View File

@ -55,7 +55,7 @@ namespace ShardingCore.Test2x
_shardingRouteManager = shardingRuntimeContext.GetShardingRouteManager(); _shardingRouteManager = shardingRuntimeContext.GetShardingRouteManager();
_shardingReadWriteManager = shardingRuntimeContext.GetShardingReadWriteManager(); _shardingReadWriteManager = shardingRuntimeContext.GetShardingReadWriteManager();
_virtualDataSource = shardingRuntimeContext.GetVirtualDataSource(); _virtualDataSource = shardingRuntimeContext.GetVirtualDataSource();
_connectionStringManager = new ActualConnectionStringManager(_shardingReadWriteManager,_virtualDataSource); _connectionStringManager = new ActualConnectionStringManager(_shardingReadWriteManager,_virtualDataSource,virtualDbContext);
_configuration = configuration; _configuration = configuration;
_entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager(); _entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager();
_tableRouteManager = shardingRuntimeContext.GetTableRouteManager(); _tableRouteManager = shardingRuntimeContext.GetTableRouteManager();

View File

@ -52,7 +52,7 @@ namespace ShardingCore.Test2x
_shardingRouteManager = shardingRuntimeContext.GetShardingRouteManager(); _shardingRouteManager = shardingRuntimeContext.GetShardingRouteManager();
_shardingReadWriteManager = shardingRuntimeContext.GetShardingReadWriteManager(); _shardingReadWriteManager = shardingRuntimeContext.GetShardingReadWriteManager();
_virtualDataSource = shardingRuntimeContext.GetVirtualDataSource(); _virtualDataSource = shardingRuntimeContext.GetVirtualDataSource();
_connectionStringManager = new ActualConnectionStringManager(_shardingReadWriteManager,_virtualDataSource); _connectionStringManager = new ActualConnectionStringManager(_shardingReadWriteManager,_virtualDataSource,virtualDbContext);
_configuration = configuration; _configuration = configuration;
_entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager(); _entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager();
_tableRouteManager = shardingRuntimeContext.GetTableRouteManager(); _tableRouteManager = shardingRuntimeContext.GetTableRouteManager();

View File

@ -55,7 +55,7 @@ namespace ShardingCore.Test3x
_shardingRouteManager = shardingRuntimeContext.GetShardingRouteManager(); _shardingRouteManager = shardingRuntimeContext.GetShardingRouteManager();
_shardingReadWriteManager = shardingRuntimeContext.GetShardingReadWriteManager(); _shardingReadWriteManager = shardingRuntimeContext.GetShardingReadWriteManager();
_virtualDataSource = shardingRuntimeContext.GetVirtualDataSource(); _virtualDataSource = shardingRuntimeContext.GetVirtualDataSource();
_connectionStringManager = new ActualConnectionStringManager(_shardingReadWriteManager,_virtualDataSource); _connectionStringManager = new ActualConnectionStringManager(_shardingReadWriteManager,_virtualDataSource,virtualDbContext);
_configuration = configuration; _configuration = configuration;
_entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager(); _entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager();
_tableRouteManager = shardingRuntimeContext.GetTableRouteManager(); _tableRouteManager = shardingRuntimeContext.GetTableRouteManager();

View File

@ -52,7 +52,7 @@ namespace ShardingCore.Test3x
_shardingRouteManager = shardingRuntimeContext.GetShardingRouteManager(); _shardingRouteManager = shardingRuntimeContext.GetShardingRouteManager();
_shardingReadWriteManager = shardingRuntimeContext.GetShardingReadWriteManager(); _shardingReadWriteManager = shardingRuntimeContext.GetShardingReadWriteManager();
_virtualDataSource = shardingRuntimeContext.GetVirtualDataSource(); _virtualDataSource = shardingRuntimeContext.GetVirtualDataSource();
_connectionStringManager = new ActualConnectionStringManager(_shardingReadWriteManager,_virtualDataSource); _connectionStringManager = new ActualConnectionStringManager(_shardingReadWriteManager,_virtualDataSource,virtualDbContext);
_configuration = configuration; _configuration = configuration;
_entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager(); _entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager();
_tableRouteManager = shardingRuntimeContext.GetTableRouteManager(); _tableRouteManager = shardingRuntimeContext.GetTableRouteManager();

View File

@ -55,7 +55,7 @@ namespace ShardingCore.Test5x
_shardingRouteManager = shardingRuntimeContext.GetShardingRouteManager(); _shardingRouteManager = shardingRuntimeContext.GetShardingRouteManager();
_shardingReadWriteManager = shardingRuntimeContext.GetShardingReadWriteManager(); _shardingReadWriteManager = shardingRuntimeContext.GetShardingReadWriteManager();
_virtualDataSource = shardingRuntimeContext.GetVirtualDataSource(); _virtualDataSource = shardingRuntimeContext.GetVirtualDataSource();
_connectionStringManager = new ActualConnectionStringManager(_shardingReadWriteManager,_virtualDataSource); _connectionStringManager = new ActualConnectionStringManager(_shardingReadWriteManager,_virtualDataSource,virtualDbContext);
_configuration = configuration; _configuration = configuration;
_entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager(); _entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager();
_tableRouteManager = shardingRuntimeContext.GetTableRouteManager(); _tableRouteManager = shardingRuntimeContext.GetTableRouteManager();

View File

@ -52,7 +52,7 @@ namespace ShardingCore.Test5x
_shardingRouteManager = shardingRuntimeContext.GetShardingRouteManager(); _shardingRouteManager = shardingRuntimeContext.GetShardingRouteManager();
_shardingReadWriteManager = shardingRuntimeContext.GetShardingReadWriteManager(); _shardingReadWriteManager = shardingRuntimeContext.GetShardingReadWriteManager();
_virtualDataSource = shardingRuntimeContext.GetVirtualDataSource(); _virtualDataSource = shardingRuntimeContext.GetVirtualDataSource();
_connectionStringManager = new ActualConnectionStringManager(_shardingReadWriteManager,_virtualDataSource); _connectionStringManager = new ActualConnectionStringManager(_shardingReadWriteManager,_virtualDataSource,virtualDbContext);
_configuration = configuration; _configuration = configuration;
_entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager(); _entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager();
_tableRouteManager = shardingRuntimeContext.GetTableRouteManager(); _tableRouteManager = shardingRuntimeContext.GetTableRouteManager();

View File

@ -58,7 +58,7 @@ namespace ShardingCore.Test6x
_shardingRouteManager = shardingRuntimeContext.GetShardingRouteManager(); _shardingRouteManager = shardingRuntimeContext.GetShardingRouteManager();
_shardingReadWriteManager = shardingRuntimeContext.GetShardingReadWriteManager(); _shardingReadWriteManager = shardingRuntimeContext.GetShardingReadWriteManager();
_virtualDataSource = shardingRuntimeContext.GetVirtualDataSource(); _virtualDataSource = shardingRuntimeContext.GetVirtualDataSource();
_connectionStringManager = new ActualConnectionStringManager(_shardingReadWriteManager, _virtualDataSource); _connectionStringManager = new ActualConnectionStringManager(_shardingReadWriteManager, _virtualDataSource,virtualDbContext);
_configuration = configuration; _configuration = configuration;
_entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager(); _entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager();
_tableRouteManager = shardingRuntimeContext.GetTableRouteManager(); _tableRouteManager = shardingRuntimeContext.GetTableRouteManager();

View File

@ -52,7 +52,7 @@ namespace ShardingCore.Test6x
_shardingRouteManager = shardingRuntimeContext.GetShardingRouteManager(); _shardingRouteManager = shardingRuntimeContext.GetShardingRouteManager();
_shardingReadWriteManager = shardingRuntimeContext.GetShardingReadWriteManager(); _shardingReadWriteManager = shardingRuntimeContext.GetShardingReadWriteManager();
_virtualDataSource = shardingRuntimeContext.GetVirtualDataSource(); _virtualDataSource = shardingRuntimeContext.GetVirtualDataSource();
_connectionStringManager = new ActualConnectionStringManager(_shardingReadWriteManager,_virtualDataSource); _connectionStringManager = new ActualConnectionStringManager(_shardingReadWriteManager,_virtualDataSource,virtualDbContext);
_configuration = configuration; _configuration = configuration;
_entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager(); _entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager();
_tableRouteManager = shardingRuntimeContext.GetTableRouteManager(); _tableRouteManager = shardingRuntimeContext.GetTableRouteManager();