MVC Cache

发布于 2015-11-30  820 次阅读


Control缓存

[OutputCache(Duration = 10)]
public class ControlController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
ViewBag.CurrentTime = System.DateTime.Now;
return View();
}

public ActionResult Index1()
{
ViewBag.CurrentTime = System.DateTime.Now;
return View();
}

}

[OutputCache(Duration = 10)]

可以加在clss上 也可以说action上

缓存配置写入config

<system.web>
16 <!--配置缓存-->
17 <caching>
18 <outputCacheSettings>
19 <outputCacheProfiles>
20 <add name="TestConfigCache" duration="10"/>
21 </outputCacheProfiles>
22 </outputCacheSettings>
23 </caching>
24 <!--配置缓存-->

使用:
[OutputCache(CacheProfile = "TestConfigCache")]

参数
1)CacheProfile:缓存使用的配置文件的缓存名称。

2)Duration:缓存时间,以秒为单位,这个除非你的Location=None,可以不添加此属性,其余时候都是必须的。

3)OutputCacheLocation:枚举类型,缓存的位置。当设置成None时,所有缓存将失效,默认为Any。

Any:页面被缓存在浏览器、代理服务器端和web服务器端;

Client:缓存在浏览器;

DownStream:页面被缓存在浏览器和任何的代理服务器端;

Server:页面被缓存在Web服务器端;

None:页面不缓存;

ServerAndClient:页面被缓存在浏览器和web服务器端;

4)VaryByParam:用于多个输出缓存的字符串列表,并以分号进行分隔。默认时,该字符串与GET方法传递的参数或与POST方法传递的变量相对应。当被设置为多个参数时,输出缓存将会为每个参数都准备一个与之相对应的文档版本。可能值包括none,*,以及任何有效的查询串或POST参数名称。

如果您不想要为不同的已缓存内容指定参数,可以将其设置为none。如果想要指定所有的已缓存内容参数,可以设置为*。

缓存依赖
<configuration>
8 <!--数据库连接字符串-->
9 <connectionStrings>
10 <add name="Conn" connectionString="server=localhost;database=wcfDemo;uid=sa;pwd=123456;" providerName="System.Data.SqlClient"/>
11 </connectionStrings>
12 <!--数据库连接字符串-->
13 <appSettings>
14 <add key="webpages:Version" value="2.0.0.0" />
15 <add key="webpages:Enabled" value="false" />
16 <add key="PreserveLoginUrl" value="true" />
17 <add key="ClientValidationEnabled" value="true" />
18 <add key="UnobtrusiveJavaScriptEnabled" value="true" />
19 </appSettings>
20 <system.web>
21 <!--配置缓存-->
22 <caching>
23 <sqlCacheDependency><!--缓存的数据库依赖节-->
24 <databases>
25 <add name="UserCacheDependency" connectionStringName="Conn" pollTime="500"/><!--Conn:数据库连接字符串的名称,name随便启名,缓存节会用到-->
26 </databases>
27 </sqlCacheDependency>
28 <outputCacheSettings>
29 <outputCacheProfiles>
30 <add name="SqlDependencyCache" duration="3600" sqlDependency="UserCacheDependency:user"/><!--UserCacheDependency:数据库依赖配置节的名称,user:数据库中需要监听的表名称-->
31 </outputCacheProfiles>
32 </outputCacheSettings>
33 </caching>
34 <!--配置缓存-->
35 <httpRuntime targetFramework="4.5" />

1)由于是缓存对数据库的依赖,此外必须包含connectionStrings的节。

2)<add name="UserCacheDependency" connectionStringName="Conn" pollTime="500"/>

connectionStringName:数据库连接字符串的名称

pollTime:监听数据库变化的周期,以毫秒为单位。即每500毫秒查看下数据库是否有变化。

3)<add name="SqlDependencyCache" duration="3600" sqlDependency="UserCacheDependency:user"/>

sqlDependency:数据依赖的节的名称+冒号+数据表名称(小写)。如果这个依赖会用到多个表,则用分号间隔开,如下所示UserCacheDependency:user;UserCacheDependency:user1

第三步:启用该数据库表的缓存依赖通知功能

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

-S localhost:数据库地址

-U sa:数据库登录名

-P 123456:数据库登录密码

-d wcfDemo:数据库的名称

-t user:表名称(小写)
111

届ける言葉を今は育ててる
最后更新于 2017-10-13