Asp. NET cache Caches

Source: Internet
Author: User

Caching introduction

If every time you enter the page query database generated page content, if the traffic is very large, the site performance will be very poor,
And if only when the first visit to query the database generated page content, and then directly output content, you can improve system performance,
This way, no matter how many people access the database only once, the database pressure is not changed
Caching is a space-for-time technology that exists in many parts of a computer and is used to save frequently used data in slow-speed devices
In a fast device, the data is fetched directly from the fast device, such as CPU level two cache, Windows file read cache
Cache failures: To ensure that data is read from the cache and consistent with data in slow data, you need to correspond in slow-speed data
Data is changed, the corresponding data in the cache is cleared
Caching is the first means of improving the performance of a website, just as the index is the first means of improving database performance


Asp. NET cache is mainly divided into:

Page caching,

Data source Cache,

Data caching

1. Page Caching
Add <% @OutputCache duration= "varybyparam=" to "none"%> tag to enable page caching.
This way, the contents of the entire page are cached, the ASP. NET code in the page, the data source will not run during the cache, but directly
Output cached page content, Duration indicates the cache time, in seconds, after which the cache is invalidated and generated again to
will be cached for 15 seconds, with some analogy, set breakpoints at Page_Load, modify database testable
The cache is present on the server, not the client, as HttpWatch still can see the request being submitted to the server

The cache is for all visitors to this page, so 1 visitors and 10,000 visitors, one visit and 1 million visits to the data
The pressure is the same
For the news page, if set as above, it will be cached in the first to see the news, because? id=2,?id=3 is just a page
Not two parameters, in order to allow different news to cache each, so you can set the varybyparam= "id", indicating that for different
The ID parameter is cached separately, and if there are multiple parameters that determine the cache, the parameter names are separated by semicolons; Can be separated, such as varybyparam= "Id;num"
If you want to create different caches for any different query strings, set varybyparam= "*", which is generally sufficient
You can also set the cache for a control in Webusercontrol like a page cache

2. Data source Caching

Set ObjectDataSource CacheDuration (cache time: seconds), enablecaching=true
This invokes the SelectMethod specified method to execute the database query every cacheduration specified time period.
All other times the data is returned directly to the cache.
Cache fixed time for the first page, the list of articles and other frequently visited pages, for the View sticker page is not suitable, assuming there are 1 million
Posts, if each post is fixed cache for 1 hours, assuming that 100,000 posts are viewed within an hour, then cache
100,000 posts, very memory-intensive, because "hundred Years a look" of the "grave" accidentally accessed once also cached for one hours, memory
This can be a "sliding window (sliding)" strategy, such as post cache for 10 minutes, if it is accessed within 10 minutes, then
The cache expiration time is modified to 10 minutes from the moment of being accessed, and so on. This often-visited post can be "long
and infrequently accessed posts will not consume the cache for a long time due to accidental access. Setup method,
Data source: cacheexpirationpolicy= "Sliding"
There seems to be a problem with sliding. No problem, sliding is only a strategy, the server will refer to

3. Cache additional (custom cache)

The caching of pages, the cache of data sources, etc., is implemented internally using Httpruntime.cache, in some page caches, data sources
The cache cannot be completed in a special cache requirement and can be directly called Httpruntime.cache for caching. In the case of the Peng Network project will be mentioned
(*) the ASP. NET cache is saved in memory by default, and can be configured to be saved to a database, and a large web site will also work with technologies such as memcached
Clears the cache. The cache may need to be emptied immediately when the cache is not invalidated, so that changes to the database are immediately reflected in the interface
Asp. NET does not provide a ready-made method, you can use hack level code

Save cache  NULL indicates cache dependent//key, value, cache dependent object, absolute expiration time, interval Cache.Insert ("User", "Xgao", Null,datetime.now.addseconds (10), TimeSpan.Zero);//Simple Save cache cache["Test"] = "This is a test!" ";//Read Cache Lbl.text = cache[" user "];

Cache dependency (dependent on file)

Principle: It is dependent on the specified file, one but the file is deleted, modified, and the cache will also be deleted

Dependent on the contents of the file CacheDependency CDEP = new CacheDependency (FilePath);

Examples are as follows: when the content of the file is unchanged, the cache is updated as the content changes.

protected void Page_Load (object sender, EventArgs e) {        if (cache["fileText"] = = null)    {    Response.Write (" The file is modified, the cache is deleted, but a new cache is created, and the next visit is available! ");    Gets the physical path of the specified file,    string filePath = Server.MapPath ("~/cachedep.txt");    Reads the specified file    string Text = File.readalltext (FilePath);    Create a cached file dependent object (the service physical path of the dependent file)    cachedependency CDEP = new CacheDependency (filePath);    Key, value, cache dependent object, no absolute expiration time, no sliding expiration time, priority, update callback function    Cache.Insert ("FileText", Text, CDEP,        System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration,         System.Web.Caching.CacheItemPriority.Normal, callback);    }    else    {    Response.Write (cache["FileText"). ToString ());}    } Cache-Dependent callback function (call some methods when cache is cleared) public void callback (string key, object value, CacheItemRemovedReason reason) {    string FilePath = Server.MapPath ("~/cachelog.txt");    String msg = "cache[" +key+ "]=" +value+ "cache is removed because:" +reason+ "\ r \ n";    File.appendalltext (FilePath, msg);}

Cache dependency (Database dependent)

dependent on database content (polling mechanism/notification mechanism)

Polling mechanism: is the FW unscheduled to check the database

1. In the Database new version table (ID, Ver field is used to save the version of a table)
2. Create a new trigger in the database (e.g. new on a news sheet)
3. Use the aspnet_regsql.exe in C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727:
Registration: Aspnet_regsql-s. -E-ED-D database name-et-t version table name
Delete: Aspnet_regsql-s. -E-D database name-dt-t version table name
To cancel the database cache dependency: Aspnet_regsql-s. -E-DD database name Version table name
List registered tables: Aspnet_regsql-s. -e-d Database name –lt
4. Configure the Web. config
5. Database Dependent objects
SqlCacheDependency CDEP = new SqlCacheDependency ("Depname", "Bankver");

Aspnet_regsql-s (server). -E (Integrated login)/-u sa-p 123-ed (boot/-dd off)-D (database name) Gssms-et (Specify cache dependent table name/-dt Disable table name)-T (table name) aticle


Database Dependent instances:

1>. The table bank is as follows:
------------------------
Idnamemaney
------------------------
1xgao1000
2zsan1
3lshi2000
------------------------

Table Bankver is as follows:
--------------
Idvernum
--------------
10
--------------

2>. To create a trigger in the bank table:

Create Trigger [Banktri]on [bank]for insert,update,deleteas  update bankver set vernum=vernum+1

3>. To turn on the cache dependency of the database (run under CMD):

Aspnet_regsql-s. -e-ed-d testdata-et-t Bankver

4>. The Web. config configuration on the website is under <system.web>:

<caching>  <sqlcachedependency enabled= "true" >    <databases>        <!--polltime as polling interval 15 seconds--    <add name= "Depname" connectionstringname= "Constr" polltime= "15000"/>    </databases >  </sqlCacheDependency></caching>

5>. Front Code:

<form id= "Form1" runat= "Server" >    <div>        <asp:gridview id= "gvbanklist" runat= "Server" >< /asp:gridview>    </div>  </form>

6>. Background code:

 protected void Page_Load (object sender, EventArgs e) {if (cache["banklist"] = = null) { Response.Write ("Data to change!") The following is read from the database!                </br> ");                DataTable dt = Getbanklist ();                Gvbanklist.datasource = DT;                Gvbanklist.databind ();                SqlCacheDependency SQLDEP = new SqlCacheDependency ("Depname", "Bankver"); Cache.Insert ("Banklist", DT, SQLDEP, System.Web.Caching.Cache.NoAbsoluteExpiration,            System.Web.Caching.Cache.NoSlidingExpiration, Cacheitempriority.normal,callback);                } else {Response.Write ("The following is a </br> read from the cache");                Gvbanklist.datasource = cache["Banklist"];            Gvbanklist.databind (); }} public void callback (string key,object Value,cacheitemremovedreason reason) {string F            Ilepath = Server.MapPath ("~/cachelog.txt"); string msg = "Database dependent cache[" + key + "]=" + Value + "Cache is removed because:" + reason + "\ r \ n";        File.appendalltext (FilePath, msg); Public DataTable Getbanklist () {String connstr = configurationmanager.connectionstrings["Conns TR "].            ConnectionString;            SqlConnection conn = new SqlConnection (CONNSTR); SqlCommand cmd = conn.            CreateCommand ();            Cmd.commandtext = "SELECT * FROM Bank";            DataSet ds = new DataSet ();            SqlDataAdapter SDA = new SqlDataAdapter (cmd); Sda.            Fill (DS); Return DS.        Tables[0]; }

Notification mechanism used: data communication FW

Asp. NET cache Caches

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.