1. 程式人生 > >Redis緩存

Redis緩存

get per ret 成功 index dex class 返回 add

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"/>

Redis緩存