Go C # Basic review: ASP. NET Cache

Source: Internet
Author: User
Tags microsoft sql server 2005 connectionstrings

This article turns from http://www.cnblogs.com/stg609/archive/2009/03/22/1418992.html

the role of caching
When you buy a computer, do you care about the CPU's level two cache? Do you want the level two cache to be a bit larger? Did you ever wonder why you had this idea? In the final analysis, for performance problems, if the cache is large, that means we can respond faster to processing data. This is like we look in the dictionary, if there is a word, you need to know its meaning, you need to open the dictionary, look up the table of contents, turn to the specified page, find the word you want, this can get the word interpretation? Unfortunately, you do not want to remember the word, when the second time you encounter the word, you have to repeat the above action? If you remember this word at that time, would it be possible to know the meaning of the word immediately? Is this very efficient?
Disadvantages of caching
If you stay for a few months in a place where information cannot be communicated, such as in the original forest, a lot of changes have taken place in these months, one of which is that the word you last queried was replaced for some particular reason. And you obviously do not know this thing, if at this moment, let you explain this word, you will be fool? What is the reason for this? It's simple, because your mind only holds the last explanation, and it doesn't get updated in time.

go to the point (I did not study in-depth, if there are shortcomings, I hope you will be very generous to enlighten us)

Example 1:
Do you want your dynamic website to have a memory brain? Maybe some friends would find it ridiculous, "is that necessary?" ” 。 If your site involves a lot of data interaction, and the frequency of the data is not very high, such as some news site, it may only need to update the news before 9:00, and then no need to change. That is to say, after 9, the data obtained by user access is the same. However, because there is no ability to provide caching, the user's every access, still cause server-side access to the database, this will not affect performance?
The effect can be achieved by configuring Page directive OutputCache in ASP. WebForm. Add the following statement to the head of your aspx file:

<%@ OutputCache duration= "Ten" varybyparam= "None"%>

There are two main attributes above (you need to configure the cache for at least these two properties):
Duration is used to define how long a page is cached (in seconds), meaning that repeated access to the page will get exactly the same data within 10 seconds.
VaryByParam Indicates whether the parameter is changed because it accepts the request (xxx.aspx?id=1), and if set to none, the expression does not change.
In this way, one of the simplest caching effects can be achieved.

Example 2:
From the above example, I believe you have a taste of the charm of the cache. However, the above effect can not be cached according to the parameters of the page, that is, no matter what parameters I pass to the page, the display is the same. For example, I have visited Xxx.aspx?id=1 and xxx.aspx?id=2 in 10 seconds, and it shows the same effect. If you want to cache based on parameters, just let varybyparam= "id" (case-insensitive). This is cached separately based on the value of the ID, which is equivalent to caching a number of different versions of the page.

Example 3:
You can use the server-side control substitution if you need to partially not be cached. The operation is simple, just drag the control onto the page and set the MethodName property to it.
The control compiles into HTML without any markup, as if it were a placeholder. It shows that the content is the method specified by MethodName. However, there are certain limitations to this approach:
1: Static method.
2: Only accept parameters of type HttpContext.
3: A value of type string must be returned.
Such as:

public static string GetCurrentTime (HttpContext context)
{
return DateTime.Now.ToString ();
}

This allows the current time to be fetched each time the page is refreshed, while the other data is cached.

Example 4:
Do you think that this way to achieve the partial cache, partial refresh effect has many limitations. If you need a more flexible way to achieve the effect of partial caching, you can do so through a user control. That is, we will need the cached data to be placed on a separate page, and then set up on that page in the way that we have shown in the previous examples. Finally, drag the set user control onto the final page. In addition, the OutputCache directive also has a shared property, and setting this property to True indicates that the output cache of the control is shared.

<%@ OutputCache duration= "Ten" varybyparam= "CategoryiD" shared= "true"%>

Example 5:
Asp. NET also provides a more convenient way to cache the variables of a page. The cache object is used. Typically used to cache data variables, such as datasets. However, if the amount of data is relatively large, it is recommended to use the hard disk cache together. It is generally better to use the cache object to save database data than to use outputcache to configure performance. However, it is best not to use the cache to store the user's login information, because the data in the cache can be replaced at any time (if you have some idea about the composition of the computer, it might be better understood).


//get the corresponding DataSet from the Cache object
dataset ds =  (dataset) cache[" Data "];

//Determines if the dataset is empty and if it is empty, the description is not in the cache.
if  (ds == null)
{
    sqlconnection conn = new  sqlconnection (configurationmanager.connectionstrings["NorthwindConnectionString"). ConnectionString);
    conn. Open ();
    sqlcommand cmd = new sqlcommand ("select * from  Products where categoryid = 1 ",  conn);
    sqldataadapter sda = new sqldataadapter (CMD);
    ds = new dataset ();
    sda. Fill (DS);
    cache["Data"] = ds;//the dataset into the Cache object
}

gridview1.datasource = ds;
Gridview1.databind ();


Example 6:
But there's always a bit of a lack of it, and it's not better to update the cache automatically when the data changes. This can be implemented in two ways, notification and polling. However, the features on MSDN that describe "notifications" are available only in the full version of Microsoft SQL Server 2005, which is non-Express (non-express). The other versions only provide polling, and I will only poll, so let's briefly introduce the way.

To use polling, configure the database, the main task of the configuration is to create a table in the database and some triggers, where we need to poll the database table object and its related information, the trigger is naturally used when the table being monitored changes in the execution. Fortunately, this series of operations can only be solved with a few simple commands. Otherwise, I might just give up halfway.
Open the Command Prompt window for vsiual Studio and enter:
Aspnet_regsql.exe-s <Server> u <Username>-P <Password>-ed-d <Database>-et-t <TABLENAME&G T
such as: Aspnet_regsql.exe-s. \msserver-u sa-p sa-ed-d northwind-et-t Products
If the run succeeds, you will be prompted:

Enable the database for the SQL cache dependency.
.
is complete.
Enable the table for the SQL cache dependency.

Then, set up some information related to SqlDependency (for example, polling time), which is set in Web. config:


<caching>
<sqlcachedependency enabled = "true" Polltime = "$" >
<databases>
<add name= "Northwind"
Connectionstringname= "NorthwindConnectionString"
Polltime = "/>"
</databases>
</sqlCacheDependency>
</caching>

The name is only required to be a convenient memory name (usually the name of the database), Polltime is the polling time (unit: milliseconds).
[Quote from MSDN: The small Polltime value increases the number of requests to the database, but it can quickly purge stale data from the cache. A larger polltime value reduces the number of requests to the database, but increases the latency between changing from background data to clearing related cache entries. Fortunately, a database request simply executes a simple stored procedure that returns only a few rows from a table with a few simple records. Try out some different polltime values for your application to find an ideal value to balance database access and data obsolescence. The minimum allowable polltime value is 500. ]
connectionStringName is the database connection name that is configured in the <connectionStrings> section. Such as:


<connectionStrings>
<add name= "NorthwindConnectionString" connectionstring= "Data source=1ac425e4d0b74f1\msserver;initial Catalog= northwind;integrated Security=true "
Providername= "System.Data.SqlClient"/>
</connectionStrings>

Finally, the duration in the OutputCache directive is "999999" to denote infinity, and a property SqlDependency is added, and the value of the genus is "database,tablename". Where database is the name specified in the Name property of the <add> element in Web. config. For example, the Products table of Northwind should be written: sqldependency= "Northwind:products". If you have two tables, write: Database:tablename;database2:tablename2.

If all the configuration is finished, you can see the effect. You will find that the cache is updated only when the data is updated. This effect is obviously better than the previous methods, but it is not possible to use this method of transition, after all, polling will still incur some costs.
[Note that some of the database names, table names, and capitalization involved in the above configuration process must be consistent, otherwise the compilation may fail.] ]


Sample package Download

Reference:
1. "Asp.net2.0 Cache and Performance" by teacher Sopoong
2.vs2005 Getting Started Substitution [VIDEO]
3.asp.net Cache Technology Summary
4. Using the ASP. NET output cache in conjunction with SQL Server
5. Using SQL cache dependencies

Go C # Basic review: ASP. NET Cache

Related Article

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.