首页 技术 正文
技术 2022年11月7日
0 收藏 357 点赞 674 浏览 1832 个字

mvc 缓存

 

对于MVC有Control缓存和Action缓存。

一、Control缓存

Control缓存即是把缓存应用到整个Control上,该Control下的所有Action都会被缓存起来。

    [OutputCache(Duration = 10)]
public class HomeController : Controller
{ // GET: Home
public ActionResult Index()
{
ViewBag.CurrentTime = DateTime.Now;
return View();
}
}
@{
ViewBag.Title = "Index";
}<h2>@ViewBag.CurrentTime</h2>

不停的刷新页面,时间会每10秒钟更新一次。

二、Action缓存

将缓存加载Action上,这样,只有加缓存的Action才会有缓存,其他的Action没有。

三、使用配置文件进行缓存配置

在MVC的Web.config文件中,可以对缓存进行相关的配置。

在system.web节点中,添加caching子节点,然后如下:

 <outputCacheSettings>
<outputCacheProfiles>
<add name="TestConfigCache" duration="10" />
</outputCacheProfiles>
</outputCacheSettings>
        [OutputCache(CacheProfile= "TestConfigCache")]
// GET: Home
public ActionResult Index()
{
ViewBag.CurrentTime = DateTime.Now;
return View();
}

四、缓存依赖

缓存数据是从数据库中某个表获取的,如果数据库中对应的表的数据没有发生改变,我们就没有必要对缓存数据进行更新,如果数据库对应的表的数据发生了变化,那么,我们相应的缓存数据就应立即更新。

那么缓存是否过期,依赖于数据库对应的表中的数据是否发生变化。这就是缓存依赖。下面我们来写一下。

我们MVC的Web.config文件中进行如下未配置:

1、首先配置数据库连接字符串:

 <connectionStrings>
<add name="sqlCon" connectionString="server=127.0.0.1;database=test;uid=sa;pwd=123456" providerName="System.Data.SqlClient" />
</connectionStrings>

2、进行缓存依赖配置:

<caching>
<sqlCacheDependency>
<databases>
<add name="PersonCacheDependency" connectionStringName="sqlCon" pollTime="500"/>
</databases>
</sqlCacheDependency>
<outputCacheSettings>
<outputCacheProfiles>
<add name="TestConfigCache" duration="3600" sqlDependency="PersonCacheDependency:Person"/>
</outputCacheProfiles>
</outputCacheSettings>
</caching>

其中pollTime为监听数据库变化的间隔时间(毫秒)

以上配置说明:库名:test,监听表名:Person。缓存时间为:3600秒即一小时。数据库依赖周期为500毫秒,即每0.5秒监听下数据库是否有变化,如果有变化则立即更新缓存。

Control中或Action中:

       [OutputCache(CacheProfile= "TestConfigCache")]
// GET: Home
public ActionResult Index()
{
ViewBag.CurrentTime = DateTime.Now;
return View();
}

这样,在一个小时内,只有Person表中的数据发生变化后,缓存才会更新,不然缓存不会更新。

五、注:

当我们配置完缓存以来后,运行我们的项目,可能会出现一下错误提示:

mvc 缓存 sqlCacheDependency 监听数据变化

这是因为我们没有对Person表启用缓存通知。

打开vs命令工具行,输入:aspnet_regsql -S localhost -U sa -P 123456 -ed -d test-et -t Person

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,484
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,899
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,732
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,485
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,125
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,286