Controllers层
public class HomeController : Controller
{
//
// GET: /Home/
// [OutputCache(Duration = 10, Location = OutputCacheLocation.ServerAndClient)]
public ActionResult Index()
{
// HttpRuntime.Cache.Remove("Ecache");//清空缓存
if (HttpRuntime.Cache["Ecache"] == null)
{
ViewData.Model = DataClass.getDataList();
ViewData["aa"] = "没有缓存从库写入!";
}
else
{
ViewData.Model = HttpRuntime.Cache["Ecache"];
ViewData["aa"] = "读缓存数据!";
}
//NoSlidingExpiration可以设置相对的过期时间,如果缓存在NoSlidingExpiration设定的时间内没有被访问,
//缓存过期一定时间内没有被访问,缓存过期,如果在一定时间内都有访问,缓存将不会过期。如在30分钟有访问Cache就不过期:
HttpRuntime.Cache.Insert("Ecache", ViewData.Model, null, DateTime.Now.AddMinutes(30), Cache.NoSlidingExpiration);
//absoluteExpiration所插入对象将过期并被从缓存中移除的时间。
return View();
}
public ActionResult Default()
{
if (BLLClass.JudgeCache())
{
ViewData.Model = DataClass.getDataList();//从数据库读
ViewData["aa"] = "AA没有缓存从库写入!";
}
else
{
ViewData.Model = BLLClass.ReadCache();//从缓存里读
ViewData["aa"] = "AA读缓存数据!";
}
BLLClass.CacheInsert(ViewData.Model,30);
return View();
}
}
}
数据层
public class DataClass
{
public static List<User_Info> getDataList()
{
List<User_Info> list = new List<User_Info>();
User_Info user;
for (int i = 1; i < 20; i++)
{
user = new User_Info();
user.ID = i;
user.Name = "User" + i.ToString();
list.Add(user);
}
return list;
}
}
BLL层,把这个写到BLL层里了。就是作一个参考
public class BLLClass
{
/// <summary>
/// Cache:创建缓存
/// </summary>
/// <param name="data"></param>
/// <param name="time">过期时间</param>
public static void CacheInsert(object data,int time)
{
HttpContext.Current.Cache.Insert("Acache", data, null, DateTime.Now.AddMinutes(time), Cache.NoSlidingExpiration);
}
/// <summary>
/// 判断缓存
/// </summary>
/// <returns></returns>
public static bool JudgeCache()
{
if (HttpRuntime.Cache["Acache"] == null)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 读取缓存
/// </summary>
/// <returns></returns>
public static object ReadCache()
{
return HttpRuntime.Cache["Acache"];
}
}