Redis缓存

public class stuController : Controller
{
BlogDBEntities db = new BlogDBEntities();

string Key = "1";
// GET: stu
public ActionResult Index()
{
//获取redis中的缓存数据
var tmp = RedisHelper.Get<List<stus>>(Key);
//如果redis中不存在数据
if (tmp == null)
{
//直接把数据在重新写入到Redis里面
var tmp1 = RedisHelper.Set(Key, db.stus.ToList());
if (tmp1)
{
var tmp2 = RedisHelper.Get<List<stus>>(Key);
return View(tmp2);
}
else
{
return View();
}

}
//判断tmp中是否有数据存在有数据的话直接返回
else
{
return View(tmp);
}
}
public ActionResult AddStu()
{
return View();
}
[HttpPost]
/// <summary>
/// 添加
/// </summary>
/// <returns></returns>
public ActionResult AddStu(stus m)
{
db.stus.Add(m);
if (db.SaveChanges() > 0)
{

RedisHelper.Set(Key, db.stus.ToList());

return Content("<script>alert('添加成功');location.href='/stu/index'</script>");
}
else
{
return Content("<script>alert('添加失败');location.href='/stu/index'</script>");
}
}
public ActionResult Del(int id)
{
var list = db.stus.Find(id);
db.stus.Remove(list);
if (db.SaveChanges() > 0)
{
RedisHelper.Remove(Key);
return Content("<script>alert('删除成功');location.href='/stu/index'</script>");
}
else
{
return Content("<script>alert('删除失败');location.href='/stu/index'</script>");
}
}
}

Redis配置

<!--Redis配置-->
<add key="RedisServiceUrl" value="127.0.01"/>
<add key="RedisServicePortNum" value="6379"/>

原文地址:https://www.cnblogs.com/htbmvc/p/8312560.html