From bf296c88ea474220e491a4347ad18f9026ae9591 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BB=A3=E7=A0=81=E7=A0=96=E5=AE=B6?= <61043157@qq.com> Date: Wed, 15 Feb 2023 22:13:01 +0800 Subject: [PATCH] =?UTF-8?q?SqlSugar=E5=A2=9E=E5=8A=A0=E7=BC=93=E5=AD=98?= =?UTF-8?q?=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ZR.Admin.WebApi/Extensions/DbExtension.cs | 14 ++++-- ZR.Admin.WebApi/Extensions/SqlSugarCache.cs | 52 +++++++++++++++++++++ 2 files changed, 63 insertions(+), 3 deletions(-) create mode 100644 ZR.Admin.WebApi/Extensions/SqlSugarCache.cs diff --git a/ZR.Admin.WebApi/Extensions/DbExtension.cs b/ZR.Admin.WebApi/Extensions/DbExtension.cs index 2540410..4025055 100644 --- a/ZR.Admin.WebApi/Extensions/DbExtension.cs +++ b/ZR.Admin.WebApi/Extensions/DbExtension.cs @@ -43,14 +43,22 @@ namespace ZR.Admin.WebApi.Extensions //...增加其他数据库 }; SugarIocServices.AddSqlSugar(iocList); + ICacheService cache = new SqlSugarCache(); SugarIocServices.ConfigurationSugar(db => { //db0数据过滤 FilterData(0); - + db.CurrentConnectionConfig.MoreSettings = new ConnMoreSettings() + { + IsAutoRemoveDataCache = true + }; + db.CurrentConnectionConfig.ConfigureExternalServices = new ConfigureExternalServices() + { + DataInfoCacheService = cache + }; iocList.ForEach(iocConfig => { - SetSugarAop(db, iocConfig); + SetSugarAop(db, iocConfig); }); }); } @@ -58,7 +66,7 @@ namespace ZR.Admin.WebApi.Extensions private static void SetSugarAop(SqlSugarClient db, IocConfig iocConfig) { var config = db.GetConnection(iocConfig.ConfigId).CurrentConnectionConfig; - + string configId = config.ConfigId; db.GetConnectionScope(configId).Aop.OnLogExecuting = (sql, pars) => { diff --git a/ZR.Admin.WebApi/Extensions/SqlSugarCache.cs b/ZR.Admin.WebApi/Extensions/SqlSugarCache.cs new file mode 100644 index 0000000..8b9595b --- /dev/null +++ b/ZR.Admin.WebApi/Extensions/SqlSugarCache.cs @@ -0,0 +1,52 @@ +using ZR.Common.Cache; + +namespace ZR.Admin.WebApi.Extensions +{ + public class SqlSugarCache : SqlSugar.ICacheService + { + public void Add(string key, V value) + { + RedisServer.Cache.Set(key, value, 3600 + RedisHelper.RandomExpired(5, 30)); + } + + public void Add(string key, V value, int cacheDurationInSeconds) + { + RedisServer.Cache.Set(key, value, cacheDurationInSeconds); + } + + public bool ContainsKey(string key) + { + return RedisServer.Cache.Exists(key); + } + + public V Get(string key) + { + return RedisServer.Cache.Get(key); + } + + public IEnumerable GetAllKey() + { + return RedisServer.Cache.Keys("*"); + } + + public V GetOrCreate(string cacheKey, Func create, int cacheDurationInSeconds = int.MaxValue) + { + if (RedisServer.Cache.Exists(cacheKey)) + { + return Get(cacheKey); + } + else + { + var restul = create(); + + Add(cacheKey, restul); + return restul; + } + } + + public void Remove(string key) + { + RedisServer.Cache.Del(key); + } + } +} \ No newline at end of file