SqlConnectionconn=newSqlConnection(strConnection);
SqlCommandcommand=newSqlCommand(strCommandText,conn); SqlCacheDependencydependency=newSqlCacheDependency(command);
//注册方法到委托,该委托是 CacheItemRemovedCallbackonRemove=newCacheItemRemovedCallback(RemovedCallback); //新增或修改一条缓存记录 Cache.Insert(strCacheKey,objAppCache,dependency,absoluteExpiration, slidingExpiration,CacheItemPriority.Default,onRemove); |
存储过程查出来的表,可以实现缓存吗?
可以将数据查询出来保存到集合中后,再用缓存数据的方式实现缓存
public static DataTable GetData() { using (SqlConnection conn = new SqlConnection(strSqlConn)) { using (SqlCommand comd = new SqlCommand("procedure_get_data", conn)) { comd.CommandType = CommandType.StoredProcedure; SqlDataAdapter sqlDa = new SqlDataAdapter(comd); DataTable dtTable = new DataTable(); if (conn.State == ConnectionState.Closed) conn.Open(); try { sqlDa.Fill(dtTable); } finally { sqlDa.Dispose(); } return dtTable; } } }
…… DataTable dtData = null; if(Cache[strCacheKey] == null) { dtData = GetData(); context.Cache.Insert(strCacheKey,dtData,null,DateTime.Now.AddMinutes(20),System.Web.Caching.Cache.NoSlidingExpiration); } else { dtData = Cache[strCacheKey] as DataTable; }
查询出来的东西放到缓存中!如果用的是MSSQL,还可以使用SQL缓存依赖,数据库中的指定一些表发生改变缓存就会失效!