前言
上一篇《C# SqlSugar框架的学习使用(六)-- 扩展用法》把一些常用的扩展用法已经做了出来,本篇就来讲一下SqlSugar高级用法中的二级缓存功能。
二级缓存功能
介绍及使用方法
二级缓存功能是对查询出来的数据进行缓存,在缓存不失效的情况下,下次同样的查询操作都会从缓存内读取。
使用缓存查询
var list=db.Queryable<Student, School>((s1, s2) => s1.Id == s2.Id).Select(s1 => s1).WithCache().ToList();//可以设置过期时间WithCache(60)
删除缓存
我们需要删除缓存也相当方便,只需要在对该表操作的时候加 RemoveDataCache 就能把查询中引用该表的缓存全部清除
db.Deleteable<Student>().Where(it => it.Id == 1).RemoveDataCache().ExecuteCommand();
Updateable和Insertable的用法是一样的。
使用技巧
解决分页缓存的难题,我们知道用到分页的表数的数据量都很大不可能使用缓存,所以提供了一个WithCacheIF的来方便的针对指定条件缓存
WithCacheIF(pageIndex<2) //只对页码小于2的进行缓存
创建二级缓存对象
创建二级缓存对象,需要在SqlSugarClient对象创建时加入自己写的实现缓存
缓存类分为两种:
.Net自带Cache的cs文件网盘下载地址:
https://pan.baidu.com/s/1Z6l9p4q-9Tuev_xWrXcFtg
Redis的cs文件网盘下载地址:
https://pan.baidu.com/s/1EAvvIffDFcnmsBW2hMIgxg
代码演示
数据源为Pos表和tvippayfl表
然后把二级缓存的两个cs文件拷贝到项目中,如下图:
HttpRuntimeCache.cs需要加引用System.Web
RedisCache.cs需要引用ServiceStack.Redis,这个可以通过Nuget包安装即可。
数据库连接里面加入二级缓存配置
/// <summary>
/// 连接数据库
/// </summary>
/// <param name="connstr"></param>
private void ConnectDb(string connstr)
{
_db = new SqlSugarClient(
new ConnectionConfig()
{
ConnectionString = _connstr,
DbType = SqlSugar.DbType.SqlServer, //设置数据库类型
IsAutoCloseConnection = true, //自动释放数据务,如果存在事务,在事务结束后释放
InitKeyType = InitKeyType.Attribute, //从实体特性中读取主键自增列信息
ConfigureExternalServices = new ConfigureExternalServices()
{
DataInfoCacheService = new HttpRuntimeCache() //RedisCache是继承ICacheService自已实现的一个类
}
});
//用来打印Sql方便你调式
_db.Aop.OnLogExecuting = (sql, pars) =>
{
TextShow(sql);
TextShow(_db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
};
}
我这里本机重做系统后还没装Redis,所以这里我们只演示.net自带的Cache
窗体界面中加入按钮功能
实现方法
将tVipPayFlow表中和Pos表中Posno字段相等的数据取出来存入缓存中
把缓存中数据的bankno字段原来为空的改为Posno的值加上Serialno的值
改完后的数据重新插入进tVipPayFlow中并删除缓存
完整代码
private void tsmnucacheinsert_Click(object sender, EventArgs e)
{
try
{
//将tVipPayFlow表中和Pos表中Posno字段相等的数据
//取出来存入缓存中
List<tVipPayFlow> list = _db.Queryable<POS, tVipPayFlow>(
(t1, t2) => t1.Posno == t2.PosNo)
.Select((t1, t2) => t2)
.WithCache()
.ToList();
TextShow("缓存了" + list.Count + "条数据");
//把缓存中数据的bankno字段原来为空的
//改为Posno的值加上Serialno的值
list.ForEach(p=>p.bankno=p.PosNo+p.SerialNo);
TextShow("更新了bankno的值");
//改完后的数据重新插入进tVipPayFlow中
int count = _db.Insertable(list)
.RemoveDataCache()
.ExecuteCommand();
TextShow("插入了" + count + "条带有bankno数据");
}
catch (Exception ex)
{
TextShow(ex.Message);
}
}
执行完后的结果
我们再查一下数据库,里面也正是多了我们插入的400条数据