由于好奇所以查了查,了解到了这个技术。
//BaseService
public int Update(List parm, Expression> columns)
{
return Db.Updateable(parm).WhereColumns(columns).RemoveDataCache().ExecuteCommand();
}
//RedisCache
public IEnumerable GetAllKey()
{
return RedisServer.Cache.Keys("Cache:SqlSugarDataCache.*");
}
SqlSugar 的缓存机制
SqlSugar
是一个功能强大的 .NET ORM 框架,它提供了一套灵活的缓存机制,旨在提高数据访问的性能。缓存机制可以避免频繁的数据库查询操作,通过缓存来加快查询速度。SqlSugar 支持多种缓存方案,并允许开发者自定义缓存策略。
SqlSugar 的缓存机制主要包括两种类型:
一级缓存(Session Cache):
DbContext
)中有效。DbContext
实例销毁时,一级缓存也会被销毁。二级缓存(Global Cache):
在 SqlSugar 中,缓存的使用非常灵活。它通过一个 CacheService
接口来定义缓存的存储和管理方式。开发者可以基于此接口自定义缓存策略,或者使用框架内置的缓存方案。
SqlSugar 提供了一个简单的基于内存的内置缓存机制,可以直接启用:
SqlSugarScope db = new SqlSugarScope(new ConnectionConfig()
{
DbType = DbType.SqlServer,
ConnectionString = "Server=.;Database=MyDb;Trusted_Connection=True;",
IsAutoCloseConnection = true,
ConfigureExternalServices = new ConfigureExternalServices()
{
DataInfoCacheService = new SqlSugar.MemoryCache() // 使用内置内存缓存
}
});
你可以实现 ICacheService
接口来自定义缓存逻辑,例如使用 Redis 作为缓存存储:
public class RedisCache : ICacheService
{
// 实现 Add、Get、Remove 等方法,以控制缓存的添加、获取、删除
public void Add(string key, V value)
{
// 实现 Redis 的缓存添加逻辑
}
public V Get(string key)
{
// 实现 Redis 的缓存获取逻辑
}
public void Remove(string key)
{
// 实现 Redis 的缓存删除逻辑
}
}
在数据库上下文配置中使用自定义缓存:
上述问题就是用了这个
SqlSugarScope db = new SqlSugarScope(new ConnectionConfig()
{
DbType = DbType.SqlServer,
ConnectionString = "Server=.;Database=MyDb;Trusted_Connection=True;",
IsAutoCloseConnection = true,
ConfigureExternalServices = new ConfigureExternalServices()
{
DataInfoCacheService = new RedisCache() // 使用自定义的 Redis 缓存
}
});
SqlSugar 提供了几个常用的方法用于管理缓存:
RemoveDataCache():用于清除特定的数据缓存,常在更新、删除操作之后调用,以防止过期数据的继续使用。
ClearCacheAll():清除所有的缓存数据,通常在需要刷新所有缓存的场景下使用。
其他:WithCache,
WithCacheIdentity,RemoveCache,EnableQueryCache,RemoveAllCache,IsCache
属性....
优点:
缺点:
缓存机制的工作原理: SqlSugar 的缓存机制依赖于缓存键(Key)的管理。缓存键通常包含特定的前缀(例如 "Cache
.*")来标识缓存项。在执行数据更新或删除操作后,RemoveDataCache
方法会被调用,以确保缓存中存储的数据与数据库的实际数据保持一致。查找和清除缓存: RemoveDataCache
方法需要清除与某个表或查询相关的缓存项。为了找到这些缓存项,SqlSugar 需要查找符合特定规则的所有缓存键。例如,通过 RedisServer.Cache.Keys("Cache:SqlSugarDataCache.*")
查找所有以 "Cache
GetAllKey()
方法就是用来获取这些符合条件的缓存键的列表。调用的具体过程: 当 RemoveDataCache
方法执行时:
ICacheService
接口中定义的 GetAllKey()
方法。RemoveDataCache
会根据这些键执行缓存删除操作,从而清除与这些键相关的缓存数据。GetAllKey()
GetAllKey
的目的是获取所有符合特定规则的缓存键,以便 RemoveDataCache
方法能够正确地定位并清除所有需要删除的缓存项。这种设计确保了在数据变化(如插入、更新、删除)时,能够及时清除相关的缓存数据,防止客户端读取到过期数据。
ICacheService
接口(使用 Redis 实现缓存查找和清除)的自定义缓存服务的其他方法内存缓存(Memory Cache)
文件系统缓存
分布式缓存(如 Memcached 或其他 NoSQL 缓存)
数据库缓存
ICacheService
接口的整个过程1.在Progaram.cs中配置数据库:
services.AddScoped(x =>
{
return new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = AppSettings.Configuration["DbConnection:ConnectionString"],
DbType = (DbType)Convert.ToInt32(AppSettings.Configuration["DbConnection:DbType"]),
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute,
ConfigureExternalServices = new ConfigureExternalServices()
{
//配置RedisCache类
DataInfoCacheService = new RedisCache()
},
MoreSettings = new ConnMoreSettings()
{
//自动清除缓存
IsAutoRemoveDataCache = true
}
});
});
namespace Meiam.System.Core
{
//配合sqlsugar在操作数据库时顺便操作redis中缓存的数据,保证两个库数据的统一
public class RedisCache : ICacheService
{
public void Add(string key, V value)
{
RedisServer.Cache.Set(key, value);
}
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("Cache:SqlSugarDataCache.*");
}
public V GetOrCreate(string cacheKey, Func create, int cacheDurationInSeconds = int.MaxValue)
{
if (ContainsKey(cacheKey))
{
return Get(cacheKey);
}
else
{
var result = create();
Add(cacheKey, result, cacheDurationInSeconds);
return result;
}
}
public void Remove(string key)
{
RedisServer.Cache.Del(key.Remove(0, 6));
}
}
}
如BaseService
...
public List GetWhere(Expression> where,
bool useCache = false,
int cacheSecond = 3600)
{
var query = Db.Queryable().Where(where).WithCacheIF(useCache,
cacheSecond);
return query.ToList();
}
#region 修改操作
public int Update(T parm)
{
return Db.Updateable(parm).RemoveDataCache().ExecuteCommand();
}
public int Update(T parm, Expression> columns)
{
return Db.Updateable(parm).WhereColumns(columns).
RemoveDataCache().ExecuteCommand();
}
...
public int Update(List parm, Expression> columns)
{
return Db.Updateable(parm).WhereColumns(columns).
RemoveDataCache().ExecuteCommand();
}
...
#endregion
#region 删除操作
public int Delete(object id)
{
return Db.Deleteable(id).RemoveDataCache().ExecuteCommand();
}
...
通常会涉及到频繁查询、不常变化或者允许短时间内数据一致性稍微延迟的数据。这种类型的数据适合缓存以提升查询性能和减少数据库的负载。