Merge pull request #365 from anjoy8/test_sqlsugar

⬆️ SqlSugar 5.1.4.158 Quartz 中SqLite锁库问题 close#360
This commit is contained in:
LemonNoCry 2024-06-12 11:54:36 +08:00 committed by GitHub
commit e06093cfbd
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
13 changed files with 242 additions and 42 deletions

View File

@ -1520,29 +1520,6 @@
</summary>
<returns></returns>
</member>
<member name="T:Blog.Core.SwaggerHelper.CustomRouteAttribute">
<summary>
自定义路由 /api/{version}/[controler]/[action]
</summary>
</member>
<member name="P:Blog.Core.SwaggerHelper.CustomRouteAttribute.GroupName">
<summary>
分组名称,是来实现接口 IApiDescriptionGroupNameProvider
</summary>
</member>
<member name="M:Blog.Core.SwaggerHelper.CustomRouteAttribute.#ctor(System.String)">
<summary>
自定义路由构造函数,继承基类路由
</summary>
<param name="actionName"></param>
</member>
<member name="M:Blog.Core.SwaggerHelper.CustomRouteAttribute.#ctor(Blog.Core.Extensions.CustomApiVersion.ApiVersions,System.String)">
<summary>
自定义版本+路由构造函数,继承基类路由
</summary>
<param name="actionName"></param>
<param name="version"></param>
</member>
<member name="T:Blog.Core.Filter.GlobalRouteAuthorizeConvention">
<summary>
Summary:全局路由权限公约
@ -1584,5 +1561,28 @@
全局路由前缀公约
</summary>
</member>
<member name="T:Blog.Core.SwaggerHelper.CustomRouteAttribute">
<summary>
自定义路由 /api/{version}/[controler]/[action]
</summary>
</member>
<member name="P:Blog.Core.SwaggerHelper.CustomRouteAttribute.GroupName">
<summary>
分组名称,是来实现接口 IApiDescriptionGroupNameProvider
</summary>
</member>
<member name="M:Blog.Core.SwaggerHelper.CustomRouteAttribute.#ctor(System.String)">
<summary>
自定义路由构造函数,继承基类路由
</summary>
<param name="actionName"></param>
</member>
<member name="M:Blog.Core.SwaggerHelper.CustomRouteAttribute.#ctor(Blog.Core.Extensions.CustomApiVersion.ApiVersions,System.String)">
<summary>
自定义版本+路由构造函数,继承基类路由
</summary>
<param name="actionName"></param>
<param name="version"></param>
</member>
</members>
</doc>

View File

@ -43,12 +43,12 @@ namespace Blog.Core.Controllers
BaseDBConfig.ValidConfig.ForEach(m =>
{
_sqlSugarClient.ChangeDatabase(m.ConfigId.ToLower());
data.response += $"库{m.ConfigId}-Model层生成{FrameSeed.CreateModels(_sqlSugarClient, m.ConfigId, isMuti)} || ";
data.response += $"库{m.ConfigId}-IRepositorys层生成{FrameSeed.CreateIRepositorys(_sqlSugarClient, m.ConfigId, isMuti)} || ";
data.response += $"库{m.ConfigId}-IServices层生成{FrameSeed.CreateIServices(_sqlSugarClient, m.ConfigId, isMuti)} || ";
data.response += $"库{m.ConfigId}-Repository层生成{FrameSeed.CreateRepository(_sqlSugarClient, m.ConfigId, isMuti)} || ";
data.response += $"库{m.ConfigId}-Services层生成{FrameSeed.CreateServices(_sqlSugarClient, m.ConfigId, isMuti)} || ";
_sqlSugarClient.ChangeDatabase(m.ConfigId.ToString().ToLower());
data.response += $"库{m.ConfigId}-Model层生成{FrameSeed.CreateModels(_sqlSugarClient, m.ConfigId.ToString(), isMuti)} || ";
data.response += $"库{m.ConfigId}-IRepositorys层生成{FrameSeed.CreateIRepositorys(_sqlSugarClient, m.ConfigId.ToString(), isMuti)} || ";
data.response += $"库{m.ConfigId}-IServices层生成{FrameSeed.CreateIServices(_sqlSugarClient, m.ConfigId.ToString(), isMuti)} || ";
data.response += $"库{m.ConfigId}-Repository层生成{FrameSeed.CreateRepository(_sqlSugarClient, m.ConfigId.ToString(), isMuti)} || ";
data.response += $"库{m.ConfigId}-Services层生成{FrameSeed.CreateServices(_sqlSugarClient, m.ConfigId.ToString(), isMuti)} || ";
});
// 切回主库

View File

@ -0,0 +1,29 @@
using Blog.Core.Common;
using Blog.Core.Controllers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
namespace Blog.Core.Api.Controllers.Test;
[Route("api/[Controller]/[Action]")]
[AllowAnonymous]
public class SqlsugarTestController : BaseApiController
{
private readonly SqlSugarScope _db;
public SqlsugarTestController(SqlSugarScope db)
{
_db = db;
}
[HttpGet]
public async Task<IActionResult> Get()
{
Console.WriteLine(App.HttpContext.Request.Path);
Console.WriteLine(App.HttpContext.RequestServices.ToString());
Console.WriteLine(App.User?.ID);
await Task.CompletedTask;
return Ok();
}
}

View File

@ -118,7 +118,7 @@
{
"ConnId": "Main2",
"DBType": 2,
"Enabled": true,
"Enabled": false,
"Connection": "WMBlog3.db", //sqlite
"Slaves": [
{
@ -265,7 +265,7 @@
"Enabled": false
},
"IpRateLimit": {
"Enabled": true
"Enabled": false
},
"EncryptionResponse": {
"Enabled": true,

View File

@ -3,7 +3,7 @@
"Name": "博客管理",
"JobGroup": "博客测试组",
"TriggerType": 1,
"Cron": "0 */5 * * * ?",
"Cron": "0 */1 * * * ?",
"AssemblyName": "Blog.Core.Tasks",
"ClassName": "Job_Blogs_Quartz",
"Remark": "",

Can't render this file because it contains an unexpected character in line 3 and column 5.

View File

@ -69,7 +69,7 @@ namespace Blog.Core.Extensions
}
else
{
if (string.Equals(config.ConfigId, MainDb.CurrentDbConnId,
if (string.Equals(config.ConfigId.ToString(), MainDb.CurrentDbConnId,
StringComparison.CurrentCultureIgnoreCase))
{
BaseDBConfig.MainConfig = config;
@ -122,6 +122,7 @@ namespace Blog.Core.Extensions
SqlSugarReuse.AutoChangeAvailableConnect(db);
});
});
services.AddTransient<SqlSugarScope>(s => s.GetService<ISqlSugarClient>() as SqlSugarScope);
}
private static string GetWholeSql(SugarParameter[] paramArr, string sql)

View File

@ -15,5 +15,7 @@ namespace Blog.Core.IServices
Task<bool> TestTranPropagationNoTran();
Task<bool> TestTranPropagationTran();
Task TestTranPropagationTran2();
Task TestTranPropagationTran3();
}
}

View File

@ -9,5 +9,6 @@ namespace Blog.Core.IServices
Task<bool> TestTranPropagation2();
Task<bool> TestTranPropagationNoTranError();
Task<bool> TestTranPropagationTran2();
Task<bool> TestTranPropagationTran3();
}
}

View File

@ -14,7 +14,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Http.Features" Version="5.0.17" />
<PackageReference Include="sqlSugarCore" Version="5.1.4.115" />
<PackageReference Include="sqlSugarCore" Version="5.1.4.158" />
<PackageReference Include="AutoMapper" Version="12.0.1" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
</ItemGroup>

View File

@ -51,21 +51,25 @@ namespace Blog.Core.Repository.UnitOfWorks
public void BeginTran()
{
Console.WriteLine("Begin Transaction Before:" + GetDbClient().ContextID);
lock (this)
{
_tranCount++;
GetDbClient().BeginTran();
}
Console.WriteLine("Begin Transaction After:" + GetDbClient().ContextID);
}
public void BeginTran(MethodInfo method)
{
Console.WriteLine("Begin Transaction Before:" + GetDbClient().ContextID);
lock (this)
{
GetDbClient().BeginTran();
TranStack.Push(method.GetFullName());
_tranCount = TranStack.Count;
}
Console.WriteLine("Begin Transaction After:" + GetDbClient().ContextID);
}
public void CommitTran()

View File

@ -8,6 +8,7 @@ using System;
using System.Threading.Tasks;
using Blog.Core.Common.DB;
using Blog.Core.Repository.UnitOfWorks;
using SqlSugar;
namespace Blog.Core.Services
{
@ -15,14 +16,17 @@ namespace Blog.Core.Services
{
private readonly IUnitOfWorkManage _unitOfWorkManage;
private readonly IBaseRepository<PasswordLib> _passwordLibRepository;
private readonly IPasswordLibServices _passwordLibServices;
private readonly ISqlSugarClient _db;
private SqlSugarScope db => _db as SqlSugarScope;
public GuestbookServices(IUnitOfWorkManage unitOfWorkManage, IBaseRepository<Guestbook> dal, IBaseRepository<PasswordLib> passwordLibRepository, IPasswordLibServices passwordLibServices)
public GuestbookServices(IUnitOfWorkManage unitOfWorkManage, IBaseRepository<Guestbook> dal,
IBaseRepository<PasswordLib> passwordLibRepository, IPasswordLibServices passwordLibServices, ISqlSugarClient db)
{
_unitOfWorkManage = unitOfWorkManage;
_passwordLibRepository = passwordLibRepository;
_passwordLibServices = passwordLibServices;
_db = db;
}
public async Task<MessageModel<string>> TestTranInRepository()
@ -193,8 +197,9 @@ namespace Blog.Core.Services
public async Task<bool> TestTranPropagationTran()
{
var guestbooks = await base.Query();
guestbooks = await base.Query();
Console.WriteLine($"first time : the count of guestbooks is :{guestbooks.Count}");
Console.WriteLine(base.Db.ContextID);
var insertGuestbook = await base.Add(new Guestbook()
{
username = "bbb",
@ -207,5 +212,68 @@ namespace Blog.Core.Services
return true;
}
[UseTran(Propagation = Propagation.Required)]
public async Task TestTranPropagationTran2()
{
await Db.Insertable(new Guestbook()
{
username = "bbb",
blogId = 1,
createdate = DateTime.Now,
isshow = true
}).ExecuteReturnSnowflakeIdAsync();
await Db.Insertable(new PasswordLib()
{
PLID = SnowFlakeSingle.Instance.NextId(),
IsDeleted = false,
plAccountName = "aaa",
plCreateTime = DateTime.Now
}).ExecuteReturnSnowflakeIdAsync();
await _passwordLibServices.TestTranPropagationTran2();
Console.WriteLine("完成");
}
public async Task TestTranPropagationTran3()
{
try
{
Console.WriteLine("Begin Transaction Before:" + db.ContextID);
db.BeginTran();
Console.WriteLine("Begin Transaction After:" + db.ContextID);
await db.Insertable(new Guestbook()
{
username = "bbb",
blogId = 1,
createdate = DateTime.Now,
isshow = true
}).ExecuteReturnSnowflakeIdAsync();
await db.Insertable(new PasswordLib()
{
PLID = SnowFlakeSingle.Instance.NextId(),
IsDeleted = false,
plAccountName = "aaa",
plCreateTime = DateTime.Now
}).ExecuteReturnSnowflakeIdAsync();
await _passwordLibServices.TestTranPropagationTran3();
db.CommitTran();
Console.WriteLine("完成");
}
catch (Exception e)
{
db.RollbackTran();
throw;
}
}
}
}

View File

@ -5,17 +5,24 @@ using Blog.Core.Common.DB;
using Blog.Core.IRepository.Base;
using Blog.Core.IServices;
using Blog.Core.Model.Models;
using Blog.Core.Repository.UnitOfWorks;
using Blog.Core.Services.BASE;
using SqlSugar;
namespace Blog.Core.Services
{
public partial class PasswordLibServices : BaseServices<PasswordLib>, IPasswordLibServices
{
IBaseRepository<PasswordLib> _dal;
private readonly IUnitOfWorkManage _unitOfWorkManage;
private readonly ISqlSugarClient _db;
private SqlSugarScope db => _db as SqlSugarScope;
public PasswordLibServices(IBaseRepository<PasswordLib> dal)
public PasswordLibServices(IBaseRepository<PasswordLib> dal, IUnitOfWorkManage unitOfWorkManage, ISqlSugarClient db)
{
this._dal = dal;
_unitOfWorkManage = unitOfWorkManage;
_db = db;
base.BaseDal = dal;
}
@ -24,6 +31,7 @@ namespace Blog.Core.Services
{
await _dal.Add(new PasswordLib()
{
PLID = SnowFlakeSingle.Instance.NextId(),
IsDeleted = false,
plAccountName = "aaa",
plCreateTime = DateTime.Now
@ -48,13 +56,33 @@ namespace Blog.Core.Services
[UseTran(Propagation = Propagation.Nested)]
public async Task<bool> TestTranPropagationTran2()
{
await _dal.Add(new PasswordLib()
await db.Insertable(new PasswordLib()
{
PLID = SnowFlakeSingle.Instance.NextId(),
IsDeleted = false,
plAccountName = "aaa",
plCreateTime = DateTime.Now
});
}).ExecuteReturnSnowflakeIdAsync();
throw new Exception("123");
return true;
}
public async Task<bool> TestTranPropagationTran3()
{
Console.WriteLine("Begin Transaction Before:" + db.ContextID);
db.BeginTran();
Console.WriteLine("Begin Transaction After:" + db.ContextID);
Console.WriteLine("");
await db.Insertable(new PasswordLib()
{
PLID = SnowFlakeSingle.Instance.NextId(),
IsDeleted = false,
plAccountName = "aaa",
plCreateTime = DateTime.Now
}).ExecuteReturnSnowflakeIdAsync();
throw new Exception("123");
return true;
}
}

View File

@ -2,25 +2,90 @@
using Quartz;
using System;
using System.Threading.Tasks;
using Blog.Core.Model.Models;
using Blog.Core.Repository.UnitOfWorks;
using SqlSugar;
/// <summary>
/// 这里要注意下,命名空间和程序集是一样的,不然反射不到
/// </summary>
namespace Blog.Core.Tasks
{
[DisallowConcurrentExecution]
public class Job_Blogs_Quartz : JobBase, IJob
{
private readonly IBlogArticleServices _blogArticleServices;
private readonly IGuestbookServices _guestbookServices;
private readonly IUnitOfWorkManage _uowm;
private readonly ISqlSugarClient _db;
private SqlSugarScope db => _db as SqlSugarScope;
public Job_Blogs_Quartz(IBlogArticleServices blogArticleServices, ITasksQzServices tasksQzServices, ITasksLogServices tasksLogServices)
public Job_Blogs_Quartz(IBlogArticleServices blogArticleServices, ITasksQzServices tasksQzServices, ITasksLogServices tasksLogServices,
IGuestbookServices guestbookServices, IUnitOfWorkManage uowm, ISqlSugarClient db)
: base(tasksQzServices, tasksLogServices)
{
_blogArticleServices = blogArticleServices;
_guestbookServices = guestbookServices;
_uowm = uowm;
this._db = db;
}
/// <summary>
/// 直接写就没有锁库 上下文ContextID一样
/// </summary>
/// <param name="context"></param>
public async Task Execute2(IJobExecutionContext context)
{
try
{
db.BeginTran();
Console.WriteLine(_uowm.GetDbClient().ContextID);
await db.Insertable(new Guestbook()
{
username = "bbb",
blogId = 1,
createdate = DateTime.Now,
isshow = true
}).ExecuteReturnSnowflakeIdAsync();
await db.Insertable(new PasswordLib()
{
PLID = SnowFlakeSingle.Instance.NextId(),
IsDeleted = false,
plAccountName = "aaa",
plCreateTime = DateTime.Now
}).ExecuteReturnSnowflakeIdAsync();
db.BeginTran();
Console.WriteLine(db.ContextID);
await db.Insertable(new PasswordLib()
{
PLID = SnowFlakeSingle.Instance.NextId(),
IsDeleted = false,
plAccountName = "aaa",
plCreateTime = DateTime.Now
}).ExecuteReturnSnowflakeIdAsync();
db.CommitTran();
Console.WriteLine(db.ContextID);
db.CommitTran();
Console.WriteLine("完成");
}
catch (Exception e)
{
db.RollbackTran();
}
}
/// <summary>
/// 但是调用其他类方法 上下文ContextID就不一样
/// </summary>
/// <param name="context"></param>
public async Task Execute(IJobExecutionContext context)
{
var executeLog = await ExecuteJob(context, async () => await Run(context));
}
public async Task Run(IJobExecutionContext context)
{
System.Console.WriteLine($"Job_Blogs_Quartz 执行 {DateTime.Now.ToShortTimeString()}");
@ -28,6 +93,8 @@ namespace Blog.Core.Tasks
// 也可以通过数据库配置,获取传递过来的参数
JobDataMap data = context.JobDetail.JobDataMap;
//int jobId = data.GetInt("JobParam");
await _guestbookServices.TestTranPropagationTran2();
}
}
}
}