SqlSugar增加缓存类

This commit is contained in:
代码砖家 2023-02-15 22:13:01 +08:00
parent 47c3e41eb1
commit bf296c88ea
2 changed files with 63 additions and 3 deletions

View File

@ -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) =>
{

View File

@ -0,0 +1,52 @@
using ZR.Common.Cache;
namespace ZR.Admin.WebApi.Extensions
{
public class SqlSugarCache : SqlSugar.ICacheService
{
public void Add<V>(string key, V value)
{
RedisServer.Cache.Set(key, value, 3600 + RedisHelper.RandomExpired(5, 30));
}
public void Add<V>(string key, V value, int cacheDurationInSeconds)
{
RedisServer.Cache.Set(key, value, cacheDurationInSeconds);
}
public bool ContainsKey<V>(string key)
{
return RedisServer.Cache.Exists(key);
}
public V Get<V>(string key)
{
return RedisServer.Cache.Get<V>(key);
}
public IEnumerable<string> GetAllKey<V>()
{
return RedisServer.Cache.Keys("*");
}
public V GetOrCreate<V>(string cacheKey, Func<V> create, int cacheDurationInSeconds = int.MaxValue)
{
if (RedisServer.Cache.Exists(cacheKey))
{
return Get<V>(cacheKey);
}
else
{
var restul = create();
Add(cacheKey, restul);
return restul;
}
}
public void Remove<V>(string key)
{
RedisServer.Cache.Del(key);
}
}
}