注意:该功能只支持实体操作,例如 字典 插入 和DataTable插入 不支持
二缓缓存是将结果集进行缓存,当SQL和参数没发生变化的时候从缓存里面读取数据,减少数据库的读取操作
ICacheService myCache = new HttpRuntimeCache(); SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = Config.ConnectionString, DbType = DbType.SqlServer, IsAutoCloseConnection = true, ConfigureExternalServices = new ConfigureExternalServices() { DataInfoCacheService = myCache //配置我们创建的缓存类 } }); db.Queryable<Student>().Where(it => it.Id > 0).WithCache().ToList();//设置缓存默认一天 db.Queryable<Student>().WithCache(1000).ToList();//设置具体过期时间
删除数据同时更新缓存,插入用和更新也一样的用法
db.Deleteable<Student>().RemoveDataCache().Where(it => it.Id == 1).ExecuteCommand(); //remove所有引用Student表的缓存,包含多表查询
我们需要创建一个 "HttpRuntimeCache" 继承 ICacheService
public class HttpRuntimeCache : ICacheService { public void Add<V>(string key, V value) { HttpRuntimeCacheHelper<V>.GetInstance().Add(key, value); } public void Add<V>(string key, V value, int cacheDurationInSeconds) { HttpRuntimeCacheHelper<V>.GetInstance().Add(key, value, cacheDurationInSeconds); } public bool ContainsKey<V>(string key) { return HttpRuntimeCacheHelper<V>.GetInstance().ContainsKey(key); } public V Get<V>(string key) { return HttpRuntimeCacheHelper<V>.GetInstance().Get(key); } public IEnumerable<string> GetAllKey<V>() { return HttpRuntimeCacheHelper<V>.GetInstance().GetAllKey(); } public V GetOrCreate<V>(string cacheKey, Func<V> create, int cacheDurationInSeconds = int.MaxValue) { var cacheManager = HttpRuntimeCacheHelper<V>.GetInstance(); if (cacheManager.ContainsKey(cacheKey)) { return cacheManager[cacheKey]; } else { var result = create(); cacheManager.Add(cacheKey, result, cacheDurationInSeconds); return result; } } public void Remove<V>(string key) { HttpRuntimeCacheHelper<V>.GetInstance().Remove(key); } }
共享你们的二级缓存实现类:
1、方便其它人用到
2、方便自已下次用到
2016 © donet5.comApache Licence 2.0