zoukankan      html  css  js  c++  java
  • mvc 缓存 sqlCacheDependency 监听数据变化

    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表中的数据发生变化后,缓存才会更新,不然缓存不会更新。

    五、注:

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

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

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

  • 相关阅读:
    编码
    TCP
    Http
    信息安全
    https基本原理
    Android之ListView异步加载图片且仅显示可见子项中的图片
    android 一些数据转换方法
    Android 关于 OnScrollListener 事件顺序次数的简要分析
    图片的内存缓存控制
    Android实现图片宽度100%ImageView宽度且高度按比例自动伸缩
  • 原文地址:https://www.cnblogs.com/sxjljj/p/11480455.html
Copyright © 2011-2022 走看看