Cache dependency (file, database)

Source: Internet
Author: User
Tags connectionstrings

Objective

The basic usage of caching is explained: I recommend looking at the ASP.

In this article, I mainly write down the general SQL cache dependency, as well as the use of MVC Filter Database cache dependency.

What is cache dependency

1. Cache: is to put the resources you want to access, in memory, occupy a certain amount of memory space, so that the user read in-memory data, thereby reducing the number of read database, or resource files, thus to your program concurrency, and the rate of return requests to improve a mechanism.

2. Cache is not timely: due to the time of the cache, the data is placed in memory, do not know whether the data source has changed, so that the information lost immediate effect.

3. Resolve the non-timeliness: To solve the second article of the non-timeliness, Microsoft is thinking of the cache depends on

4. Cache dependency: is a mechanism by which the cache is notified of the expiration of a cache by monitoring the read and write of a dependency (file or database). For example, a dependency is a 123.txt file, and the cached data is data in 234.txt, so the caching mechanism can remove data from the cached 234.txt file by monitoring the change in the data in the 123.txt file. Feel the drag, or the code more to force.

cache Dependencies (Files)
            The file cache depends on            if (cache. Get ("key") = = null)//If the data in the dependency changes, this is notified that the cache is emptied (the system completes emptying)            {                CacheDependency dp = new CacheDependency ( Server.MapPath ("/data/123.txt"));//Establish cache dependency DP                string str = doiofile.readfiles ("/data/111.txt");                Cache. Insert ("Key", STR, DP);            }            Response.Write (Cache. Get ("key"));   If the content of the 123.txt file is constant, the data in the cache is read, and once the data in the 123.txt file is changed, the data in the 111.txt file is re-read.

Effect: The cached data is data in 111.txt, the data in 111.txt changes, the key of the cache will not be emptied, that is, still show the data before the change. However, if the data in the cache dependency 123.txt changes, the cache is emptied immediately, and the new data in the cache is re-written. That's the benefit of caching dependencies that you can try and I don't fool you.

Cache Dependencies (folders)
            The folder cache depends on            if (cache. Get ("key") = = null)//If the data in the dependency changes, this is notified that the cache is emptied (the system completes emptying)            {                CacheDependency dp = new CacheDependency ( Server.MapPath ("/data"));//Establish cache dependency DP                 string str = doiofile.readfiles ("111.txt");                Cache. Insert ("Key", STR, DP);            }            Response.Write (Cache. Get ("key"));   If the content of the 123.txt file is constant, the data in the cache is read, and once the data in the 123.txt file is changed, the data in the 111.txt file is re-read.

Effect: Here/data is a folder, he directly under the data all the first level files (that is not the nested folder files) If there is a change, will trigger the notification, empty the cache.

Cache dependencies (multiple files)
            Multi-File Dependency            if (cache. Get ("key") = = null)//If the data in the dependency changes, this is notified that the cache is emptied (the system completes emptying)            {                CacheDependency dp1 = new CacheDependency ( Server.MapPath ("/data/123/123.txt")); Here is the monitor file or directory                cachedependency DP2 = new CacheDependency (Server.MapPath ("/data/123.txt"));                cachedependency[] DPS = new cachedependency[] {DP1, DP2};                AggregateCacheDependency aDp = new AggregateCacheDependency (); Multiple dependency                Adp.add (DPS);                String str = doiofile.readfiles ("111.txt");                Cache. Insert ("Key", str, aDp);            }            Response.Write (Cache. Get ("key"));  

Effect: Any one of the files in the dependency is changed, the cache is emptied, and the new cache is written.

Caching in MVC

The use of the cache in MVC is relatively simple, just use the filter to define on the line, the other I do not tired, and WebForm is no different.

        [OutputCache (Duration = 20)]//define cache, seconds, Duration is required public        ActionResult Index ()        {            string str = Doiofile.readfiles ("/111.txt");            Response.Write (str);            return View ();        }

Detailed configuration See: http://msdn.microsoft.com/zh-cn/library/system.web.mvc.outputcacheattribute.aspx

Cache dependency (database table)

This is a bit cumbersome, then do.

1. Open the project configuration file

<connectionStrings>         <add name= "Am_weixinweb" connectionstring= "Data source=192.168.1.200;initial catalog=am_weixinweb;uid=sa;password=lh1234; "  />  </connectionStrings>
<system.web>    <caching>      <sqlcachedependency enabled= "true" Polltime= "$" >        < databases>          <add name= "Test" connectionstringname= "Am_weixinweb"/>        </databases>      </ Sqlcachedependency>    </caching>

Note:polltime, milliseconds, consciousness is every 2 seconds to detect the database, check whether the table has changed. connectionStringName the database link string.

2. Start Database Cache dependency

In the C drive, search for the tool aspnet_regsql.exe

In the command CD: Under the file that runs to this tool, type the following command

Aspnet_regsql-c "Data source=;initial catalog=codematic;user id=sa;password="-ed-et-t "T_table "

Parameter:-C followed by the connection string,-t followed by the table name that established the cache dependency

Tool command parameter list see: http://msdn.microsoft.com/zh-cn/library/ms229862

3. Using cache dependencies

            SQL cache relies on            DataSet ds = new DataSet ();            if (cache. Get ("key") = = null)            {                string constr = Doxml.readwebconfigconnectionstrings ("Am_weixinweb");                SqlConnection conn = new SqlConnection (CONSTR);                String sql = "SELECT top (1) reccontent from Am_recproscheme";                SqlCommand cmd = new SqlCommand (SQL, conn);                SqlDataAdapter SDA = new SqlDataAdapter (cmd);                Sda. Fill (ds, "tb1");                SqlCacheDependency dep = new SqlCacheDependency ("Test", "Am_recproscheme");  The cache configuration key for the test corresponds to the configuration item, followed by the database table name                cache. Insert ("Key", DS. tables["TB1"]. rows[0]["Reccontent"]. ToString (), DEP);            }            Response.Write (Cache. Get ("key"));

Effect: The data in the table Am_recproscheme in the database am_weixinweb is changed, then the cache is emptied and re-written.

Configure cache dependencies in the MVC filter (database)

1. Open the project configuration file

<connectionStrings>        <add name= "Am_weixinweb" connectionstring= "Data source=192.168.1.200;initial catalog=am_weixinweb;uid=sa;password=lh1234; "  />  </connectionStrings>
<caching>      <sqlcachedependency enabled= "true" Polltime= "$" >        <databases>          <add Name= "Test" connectionstringname= "Am_weixinweb"/>        </databases>      </sqlCacheDependency>    </caching>

Note:polltime, milliseconds, consciousness is every 2 seconds to detect the database, check whether the table has changed. connectionStringName the database link string.

2. Configure Filters

        MVC cache Dependency        [OutputCache (Duration = SqlDependency = "Test:am_recproscheme")]//test: The key configured for the cache followed by the cache dependency table        Public ActionResult Index ()        {                       Response.Write (db). Am_recproscheme.firstordefault (). reccontent);            return View ();        }

Effect: The data in the table Am_recproscheme in the database am_weixinweb is changed, then the cache is emptied and re-written.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.